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