EF:如何在一个事务中使用相同的NEW对象添加2个对象

时间:2015-12-02 15:36:40

标签: entity-framework

我的网络应用程序使用EF作为ORM。问题是,当我想添加具有相同地址的House和Home对象时(Address对象在数据库中也是新的),出现错误:

INSERT语句与FOREIGN KEY约束冲突" FK_dbo.Houses_dbo.Houses_AddressId"。 冲突发生在数据库" devDB",table" dbo.Houses",column' Id'。

执行插入的代码:

Address address = new Address(){Id=-1, AddressValue ="AAA"};
Home home = new Home(){Address = address }
Office office = new Office(){Address = address }

context.Offices.Add(office);
context.Homes.Add(home);
context.SaveChanges();

2 个答案:

答案 0 :(得分:1)

可能存在问题,因为Address具有EntityState Untracked。解决方案是添加Address保存,然后将保存的实例添加到其他实体:

Address address = new Address(){ Id=-1, AddressValue ="AAA" };
context.Address.Add(address );
context.SaveChanges();

Home home = new Home(){Address = address }
Office office = new Office(){Address = address }

context.Offices.Add(office);
context.Homes.Add(home);
context.SaveChanges();

如果某些进一步的保存操作失败,为了防止您拥有孤立的地址,请创建Transaction

using(var trans = context.Database.BeginTransaction())
{
    try
    {
        //...
        trans.Commit();
    }
    catch(Exception)
    {
        trans.Rollback();
    }
}

答案 1 :(得分:0)

我认为这是因为您在地址中指定了否定ID:

Address address = new Address(){Id=-1, AddressValue ="AAA"};

主键ID不能为负

如果您使用的是Code-first,那么只要您已将ID配置为自动增量,就会自动生成ID。否则,您需要计算一个正的唯一ID。

相关问题