Entity framework 4 实体框架:x27;附加以下实体时是否引发异常?

Entity framework 4 实体框架:x27;附加以下实体时是否引发异常?,entity-framework-4,Entity Framework 4,据我所知,EntityCollection.Attach和EntityReference.Attach只能创建数据库中已经存在的关系。换句话说,如果Address.EmployeeID==Employee.EmployeeID,则以下代码将起作用: Employee employee = context.Employees.First(); Address address = context.Addresses.First(); employee.

据我所知,
EntityCollection.Attach
EntityReference.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
但根据以下代码示例,
EntityCollection.Attach
EntityReference.Attach
也可用于创建数据库中不存在的关系:

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.Attach
EntityReference.Attach
只能创建数据库中已经存在的关系,因此从另一个线程获取的代码示例应该引发异常,这是正确的吗


谢谢

是的,我认为这只是打字错误或作者写了一些不完整的东西

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

你会得到50分,但你能回答我这个问题吗?这样我就可以完全确定了:所以我正确地假设EntityCollection.Attach和EntityReference.Attach只能创建数据库中已经存在的关系?