2014-03-03 28 views
0

我有兩個實體在DbInitialize類中使用外鍵。代碼首先

public class Datatype 
{ 
    [Key] 
    public int Id { get; set; } 
    [StringLength(96)] 
    public string DataTypeName { get; set; }   
} 

public class Attribute 
{ 
    [Key] 
    public int Id { get; set; } 
    [StringLength(96)] 
    public string Attribute_Name { get; set; } 

    [ForeignKey("Datatype")] 
    public int? DatatypeId { get; set; } 
    public virtual Datatype Datatype { get; set; } 
} 

在數據庫初始化我有這樣的代碼

Datatype dt = new Datatype(); 
    dt.DataTypeName = "text"; 
    context.datatypes.Add(dt); 
//Above code is working fine. And After execution I can see 
//in records a row.. with id=1 and datatype=text 
    Attribute at = new Attribute(); 
    at.Attribute_Name = "Description"; 
    //at.DatatypeId = 1;     But if I uncomment this line 
    context.attributes.Add(at);   // Then This Gives Following Error 

The INSERT statement conflicted with the FOREIGN KEY constraint 
"FK_dbo.Attributes_dbo.Datatypes_DatatypeId". The conflict occurred in database 
"dyescan", table "dbo.Datatypes", column 'Id' 

回答

1

假設上面的代碼執行任意的兩個對象的已保存之前到數據庫,那麼它不會工作,因爲你的對象'dt'在它被保存到數據庫之前不會有1的ID,因此你不能關聯屬性'1'仍然!

相反,你不應該設置「DatatypeId」,但簡單地將「數據類型」,像這樣:

at.Datatype = dt; 

這將使實體框架,找出相關的實際外鍵應有/會是什麼時候的SaveChanges叫做。

+0

雖然問題是別的,因爲在生成數據庫中,我可以看到所有其他表都按照我在mycontext類中編寫的名稱進行命名。例如除了'datatypes'外,它的名稱爲'data_type',但根據'mycontext'應該是'datat_types',但是感謝您的解決方案正在工作。 – Sami