参照完整性约束冲突。从属角色具有多个具有不同值的主体 [英] Referential integrity constraint violation. A Dependent Role has multiple principals with different values

查看:160
本文介绍了参照完整性约束冲突。从属角色具有多个具有不同值的主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在EF6.0中将多个实体添加到dbcontext中时,出现以下错误,如果我仅添加第一个实体,则保存得很好,如果添加第二个实体,则会得到错误。

I get the following error when I add more than one entity to a dbcontext in EF6.0, if i only add the first, it saves perfectly, if i add a second one then I get the error.

错误:


引用完整性约束冲突。从属角色具有多个具有不同值的主体。

"Referential integrity constraint violation. A Dependent Role has multiple principals with different values."

代码

using (var context = new ListingLocatorContext())
{
    var listing1 = new Listing
    {
        UserID = 1,
        ListingDate = DateTime.Now,
        ExpiryDate = DateTime.Now,
        Address = string.Empty,
        PostalCode = string.Empty,
        IsApproved = true,
        CityID = 71,
        IsTop = true,
        IsActive = true,
        ViewCount = 0
    };

    listing1.ListingTypes.Add(new ListingType
    {
        TypeID = 4
    });

    var listing2 = new Listing
    {
        UserID = 1,
        ListingDate = DateTime.Now,
        ExpiryDate = DateTime.Now,
        Address = string.Empty,
        PostalCode = string.Empty,
        IsApproved = true,
        CityID = 71,
        IsTop = true,
        IsActive = true,
        ViewCount = 0
    };

    listing2.ListingTypes.Add(new ListingType
    {
        TypeID = 5
    });

    context.Listings.Add(listing1);
    context.Listings.Add(listing2);

    context.SaveChanges();
}

DB图

推荐答案

尝试替换这两个语句:

listing1.ListingTypes.Add(new ListingType {
    TypeID = 4
});

listing2.ListingTypes.Add(new ListingType {
    TypeID = 5
});

var listingType1 = new ListingType {
    TypeID = 4,
    Listing = listing1
};
var listingType2 = new ListingType {
    TypeID = 5,
    Listing = listing2
};

context.ListingTypes.Add(listingType1);
context.ListingTypes.Add(listingType2);

这篇关于参照完整性约束冲突。从属角色具有多个具有不同值的主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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