实体框架:不应该附加以下实体抛出异常?

时间:2011-11-15 19:30:35

标签: entity-framework-4

据我所知,EntityCollection.AttachEntityReference.Attach只能创建数据库中已存在的关系。换句话说,如果Address.EmployeeID == Employee.EmployeeID,则以下代码将起作用:

        Employee employee = context.Employees.First();
        Address address = context.Addresses.First();
        employee.Addresses.Attach(address);

但是如果Address.EmployeeID != Employee.EmployeeID,则代码将抛出异常:

        Employee employee = context.Employees.First();
        Address address = context.Addresses.First();
        employee.Addresses.Attach(address); // System.InvalidOperationException: A 
                                            // referential integrity constraint
                                            // violation occurred

但根据以下thread中的代码示例,EntityCollection.AttachEntityReference.Attach也可用于创建DB中不存在的关系:

var existingPerson = ctx.Persons.SingleOrDefault(p => p.Name = "Joe Bloggs" };
var myAddress = ctx.Addresses.First(a => a.PersonID != existingPerson.PersonID);
existingPerson.Addresses.Attach(myAddress);
// OR:
myAddress.PersonReference.Attach(existingPerson)
ctx.SaveChanges();

因此,我假设EntityCollection.AttachEntityReference.Attach只能创建数据库中已存在的关系,并且从其他线程获取的代码示例应该抛出异常,我是否正确?

谢谢

1 个答案:

答案 0 :(得分:1)

是的,我认为这只是一个输入错误,或者作者写了一些不完整的内容。

var existingPerson = ctx.Persons.SingleOrDefault(p => p.Name = "Joe Bloggs" };
var myAddress = ctx.Addresses.First(a => a.PersonID == existingPerson.PersonID);
existingPerson.Addresses.Attach(myAddress);
// OR:
myAddress.PersonReference.Attach(existingPerson)
ctx.SaveChanges();