实体框架不添加[Key]

时间:2014-09-20 10:30:38

标签: c# entity-framework

我创建了一个包含此实体的模型:

enter image description here

现在,当EF顺便说一下。 CodeGenerator正在为此实体生成代码,缺少PK注释:

public partial class tLieferscheinPos
{
    public int kLieferscheinPos { get; set; }
    public int kLieferschein { get; set; }
    public Nullable<int> kBestellPos { get; set; }
    public Nullable<decimal> fAnzahl { get; set; }
}

当我现在使用connectionString创建DbContext时(其中eazybusinessEntitisDbContext):

this.context = new eazybusinessEntities(connStr);            

EF将始终更新我的数据库 - 或抛出异常(当我在throw new UnintentionalCodeFirstException();中移除OnModelCreating时):

One or more validation errors were detected during model generation:

\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'tLieferscheinPos' has no key defined. Define the key for this EntityType.   
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'tLieferscheinPos' is based on type 'tLieferscheinPos' that has no keys defined.

当我将[Key]添加到属性kLieferscheinPos时,它正常工作。但是,当我从模型中重新创建代码时,这种变化将永远被覆盖。

我该怎么做才能正确解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以在上下文类中声明密钥...

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<tablename>().HasKey(e => e.keycolumnname);
 }

如果您正在使用视图模型,则可以在那里声明[key] ...

public class products
{
    [Key]
    public int productid { get; set; }
    ...
}