【问题标题】:How to add a Primary Key with fluent API - Entity Framework EF 4.x Code First如何使用流畅的 API 添加主键 - Entity Framework EF 4.x Code First
【发布时间】:2012-05-23 12:05:18
【问题描述】:

我需要映射一些自动生成的类,出于明显的原因我不想更改它们(它是自动生成的!)。

那么是否有可能使用实体框架的流畅 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.

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

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>();
    }
}

【问题讨论】:

    标签: .net database entity-framework code-first


    【解决方案1】:

    你可以使用HasKey方法。

    builder.Entity<FooBar>().HasKey(...);
    

    【讨论】:

    • 据我所知仅适用于现有物业
    • 是的。 Beucase Entity Framework 中的每个实体都必须有一个 key 属性。
    • @cincura.net:你好,每个表都有主键是EF的属性吗?我的意思是我不能在 EF 中没有主键的表?
    • 是的。每个实体都需要有一个密钥。顺便说一句,这是一个完全不同的问题。也许更好地问新的,我会尽快回复。
    猜你喜欢
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多