Error Seeding Database, foreign key issue

不羁的心 提交于 2019-12-20 04:26:06

问题


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?


回答1:


What is happening is your objects all have the default int value (0) for their primary key. When you add them to the context, EF detects this and throws an error (two objects of the same type cannot have the same key, in this case, 0. I assume your primary key fields in the database are set as IDENTITY columns and will auto increment +1 on insert. This may sound odd, but you need to give your objects placeholder IDs which will be replaced on insert with the IDENTITY values.

new Color{ColorId = 1, Name="Red"},
new Color{ColorId = 2, Name="White"}
new Type{TypeId = 1, Name="Hammer", ...}
new Type(TypeId = 2, Name="Electric", ...}


来源:https://stackoverflow.com/questions/11602683/error-seeding-database-foreign-key-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!