参照完整性约束违规。依赖角色具有多个具有不同值的主体

时间:2013-12-30 04:51:17

标签: entity-framework

当我在EF6.0中向dbcontext添加多个实体时出现以下错误,如果我只添加第一个,它会完全保存,如果我添加第二个然后我就会收到错误。

错误:

  

“参照完整性约束违规。从属角色具有多个具有不同值的主体。”

代码

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 Diagram

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试替换这两个陈述:

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);