.net - 如何使用流畅的 API 添加主键 - Entity Framework EF 4.x Code First

标签 .net database entity-framework code-first

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

那么是否有可能使用 Entity Framework 的流畅 API(在我的例子中是 4.3)定义主键?由于 NULL 值,将属性作为 ComplexType 处理会导致 DbUpdateExcetion。在生成的类中添加主键可能是一种解决方案,但不适合我,POCOs 必须保持不变。请帮助!谢谢。

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

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

最佳答案

您可以使用 HasKey方法。

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

关于.net - 如何使用流畅的 API 添加主键 - Entity Framework EF 4.x Code First,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10719543/

相关文章:

mysql - 如何将营业时间存储在数据库中以便在打开时能够进行搜索?

java - 将 Hibernate 实体重构为子类

asp.net-mvc - 使用存储库模式支持多个提供者

sql - Entity Framework Azure SaveChanges - 日期时间,错误一小时

.net - Entity Framework : ObjectSet and its (generics) variance

c# - 事件查看器应用程序崩溃 - 解密错误消息

mysql - 逐一获取列数据

c# - 计算平均值时是否可以使用 Skip and Take?

c# - 无法使用 GET 请求发送具有此动词类型的内容正文

c# - 不活动后出现故障的 WCF 双工回调 - 使长时间运行的推送通知保持事件状态