简体   繁体   English

EF 4.1:使用Fluent映射从代码优先查找关键属性类型

[英]EF 4.1: Find Key Property Type from Code First with Fluent Mapping

I'm using EF 4.1 Code First, with a Fluent Mapping: 我先使用EF 4.1代码,并使用Fluent映射:

Entity: 实体:

public class MyClass
{
    public int MyClassID { get; set; }
    public string Name { get; set; }
}

Mapping: 制图:

public class MyClassMapping: EntityTypeConfiguration<MyClass>
{
    public MyClassMapping()
    {
        Map(t => t.ToTable("MyClass"))
             .HasKey(t => t.MyClassID);

        Property(t => t.MyClassID)
             .IsRequired()
             .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(t => t.Name)
             .IsRequired()
             .HasMaxLength(200);
    }
}

Given this configuration (and a number of similar declarations/mappings for other entities), if I know the type of the entity class (ie MyClass ) is it possible to get the Type and Name of the key property of the entity class? 给定此配置(以及其他实体的许多类似声明/映射),如果我知道实体类的类型(即MyClass ),是否可以获取实体类的键属性的类型和名称? - Since I've defined it in the mapping, shouldn't I be able to get this back from either IDbSet for MyClass or my DbContext derived Entity container? -由于我已经在映射中定义了它,因此我是否应该既不IDbSet MyClass DbContext或从DbContext派生的Entity容器中DbContext它呢?

I'm not interested in just assuming that keyname = classname + "ID" or similar - how is it done properly from the mappings? 我对仅假设keyname = classname + "ID"或类似keyname = classname + "ID"不感兴趣-如何从映射中正确完成?

You need to access the MetadataWorkspace 您需要访问MetadataWorkspace

public class MyContext : DbContext
{

    public void Test()
    {            
        var objectContext = ((IObjectContextAdapter)this).ObjectContext;

        var mdw = objectContext.MetadataWorkspace;

        var items = mdw.GetItems<EntityType>(DataSpace.CSpace);
        foreach (var i in items)
        {
            Console.WriteLine("Class Name: {0}", i.Name);
            Console.WriteLine("Key Property Names:");
            foreach (var key in i.KeyMembers)
            {
                Console.WriteLine(key.Name);
            }
        }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM