I have built out my models using POCO. When I go to seed my database I get:
Unable to determine the principal end of the 'CSP.Models.Type_Color' relationship. Multiple added entities may have the same primary key
Here's the models in question:
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; }
}
Most of the markup I did after reading suggestions.
My seed code that is getting the error is here:
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();
I also tried adding each value to the context and then saving. I got this error after it tried saving the type entity:
[System.Data.SqlClient.SqlException] = {"The INSERT statement conflicted with the FOREIGN KEY constraint \"Type_Color\". The conflict occurred in database \"TestTools\", table \"dbo.Colors\", column 'ColorId'.\r\nThe statement has been terminated."}
What am I missing?