2014-09-20 123 views
1

我創建了被包含該實體的模型:實體框架不添加[關鍵]

enter image description here

現在,當EF BTW。該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(其中eazybusinessEntitisDbContext)創建的DbContext現在運行:

this.context = new eazybusinessEntities(connStr);    

EF會隨時更新我的​​數據庫 - 或者拋出異常(當我在OnModelCreating刪除throw new UnintentionalCodeFirstException();):

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

好吧,是不是'kLieferscheinPos'表中的**主鍵**列?它應該是**! (然後,我認爲EF會將其識別爲關鍵字並據此設置屬性) – 2014-09-20 10:38:47

+0

您是否在EF中使用模型第一種方法? – 2014-09-20 10:41:42

+0

如果你命名密鑰列kLieferscheinPosID它會生成密鑰屬性呢? – pln 2014-09-20 10:51:19

回答

0

你可以聲明你的上下文類中的關鍵...

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

如果您使用的是視圖模型,你可以聲明[關鍵]那裏...

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