我创建了一个包含此实体的模型:
现在,当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时(其中eazybusinessEntitis
是DbContext
):
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
时,它正常工作。但是,当我从模型中重新创建代码时,这种变化将永远被覆盖。
我该怎么做才能正确解决这个问题?
答案 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; }
...
}