我已經使用POCO構建了我的模型。當我開始播種我的數據庫時,我得到:錯誤播種數據庫,外鍵問題
無法確定'CSP.Models.Type_Color'關係的主體結束。多補充實體可能具有相同的主鍵
這裏的模型問題:
public class Type
{
[Key]
[ScaffoldColumn(false)]
public int TypeId { get; set; }
[Required(ErrorMessage = "A Type Name is Required")]
[Display(Name="Type")]
public string Name { get; set; }
public int ColorId { get; set; }
public bool Other { get; set; }
//Navigations
[ForeignKey("ColorId")]
public virtual Color Color { get; set; }
public virtual List<Tools> tools { get; set; }
}
public class Color
{
[Key]
[ScaffoldColumn(false)]
public int ColorId { get; set; }
[Required(ErrorMessage = "A name is required")]
public string Name { get; set; }
public string Description { get; set; }
//navigation
public virtual List<Type> Types { get; set; }
}
大多數標記我讀的建議後所做的。
所得到的錯誤我的種子代碼是在這裏:
var colors = new List<Color>
{
new Color{Name="Red"},
new Color{Name="White"}
};
var types = new List<Type>
{
new Type{ Name="Hammer", Color = colors.Where(ws => ws.Name=="Red").Single()},
new Type{ Name= "Electric", Color = colors.Where(ws => ws.Name=="Red").Single()}
};
new List<Tool>
{
new Wine{ Maker= Maker.Single(v => v.Name=="HammerCo"), Type= types.Single(wt => wt.Name=="hammer")},
}
}.ForEach(a => context.Tools.Add(a));
context.SaveChanges();
我也嘗試添加每個值範圍內,然後保存。在嘗試保存類型實體後,我得到了這個錯誤:
[System.Data.SqlClient.SqlException] = {「INSERT語句與FOREIGN KEY約束衝突」Type_Color \「衝突發生在數據庫\」 TestTools \「,table \」dbo.Colors \「,'ColorId'列。\ r \ n聲明已終止。」}
我錯過了什麼?
你拼寫爲「錘」沒有大寫的H第二次除此之外,嘗試使ColorID爲int?('Nullable') –
Dabblernl
2012-07-22 19:27:07