如何使用流畅的API添加主键 - 实体框架EF 4.x代码优先

Han*_*ans 4 .net database entity-framework code-first

我需要映射一些自动生成的类,我不想改变它们的显示(它是自动生成的!).

那么是否有可能使用实体框架的流畅API定义主键(在我的情况下为4.3)?由于NULL值,将属性处理为ComplexType会导致DbUpdateExcetion.向生成的类添加主键可能是一种解决方案,但不适合我,POCO必须保持不变.请帮助!谢谢.

目前我忽略了属性,因为......

ModelValidationException 
EntityType 'Attribute' has no key defined.  Define the key for this EntityType.
EntitySet 'Attributes' is based on type 'Attribute' that has no keys defined.
Run Code Online (Sandbox Code Playgroud)

这是一个简短的示例代码:

public class Item
{
   public ID {set;get;}
   public Attribute[] Attributes {set;get;}
} 
public class Attribute
{
   public SomeComplexType misc1 {set; get;}
   public SomeComplexType misc2 {set; get;}
}

public class ItemDb : DbContext
{
    public ItemDb(string connection) : base(connection)  {}

    public DbSet<Item> Items { get; set; }

    protected override void OnModelCreating(DbModelBuilder builder)
    {
      // currently I am ignoring the Attributes 
        builder.Ignore<Attributes>();
    }
}
Run Code Online (Sandbox Code Playgroud)

cin*_*net 6

您可以使用HasKey方法.

builder.Entity<FooBar>().HasKey(...);
Run Code Online (Sandbox Code Playgroud)