种子数据库错误,外键问题 [英] Error Seeding Database, foreign key issue

查看:105
本文介绍了种子数据库错误,外键问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用POCO建立了我的模型。当我去种子我的数据库时,我得到:



无法确定CSP.Models.Type_Color关系的主体结束。多个添加的实体可能具有相同的主键



以下是有问题的模型:

  public class Type 
{
[Key]
[ScaffoldColumn(false)]
public int TypeId {get;组; }

[必需(ErrorMessage =A类型名称是必需的)]
[Display(Name =Type)]
public string Name {get;组; }

public int ColorId {get;组; }
public bool其他{get;组; }

//导航
[ForeignKey(ColorId)]
public virtual Color Color {get;组; }
public virtual List< Tools>工具{get;组;



public class Color
{
[Key]
[ScaffoldColumn(false)]
public int ColorId {get;组; }

[必需(ErrorMessage =需要名称)]
public string Name {get;组; }

public string描述{get;组; }

// navigation
public virtual List< Type>类型{get;组; }
}

阅读建议后我做的大部分标记。



我收到错误的种子代码在这里:

  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 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\中,表\dbo.Colors\,列'ColorId'。\\\
n这个语句已被终止。}



我缺少什么?

解决方案

发生的是你的对象它们的主键具有默认的int值(0)。当您将它们添加到上下文中时,EF会检测到这个错误并抛出一个错误(两个相同类型的对象不能具有相同的密钥,在这种情况下为0.我认为数据库中的主键字段设置为IDENTITY列,并将会自动增量+1插入,这可能听起来很奇怪,但是您需要给出您的对象占位符ID,该ID将被替换为IDENTITY值。

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


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?

解决方案

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", ...}

这篇关于种子数据库错误,外键问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆