0

As far as I can tell, EntityCollection.Attach and EntityReference.Attach can only create relationships that already exists in the database. In other words, if Address.EmployeeID == Employee.EmployeeID, then the following code will work:

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

But if Address.EmployeeID != Employee.EmployeeID, then the code will throw an exception:

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

But according to a code example taken from the following thread, EntityCollection.Attach and EntityReference.Attach can also be used to create a relationship that doesn't exist in a 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();

So am I correct in assuming that EntityCollection.Attach and EntityReference.Attach can only create relationships that already exists in the database, and as such code example taken from the other thread should throw an exception?

Thank you

Community
  • 1
  • 1
user702769
  • 2,435
  • 2
  • 25
  • 34

1 Answers1

1

Yes, I think it's just a typing mistake or author has written something incomplete.

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();
Akash Kava
  • 39,066
  • 20
  • 121
  • 167
  • You will get 50 points, but could you just answer me this so I can be completely sure: so I'm correct in assuming that EntityCollection.Attach and EntityReference.Attach can only create relationships that already exists in a database? – user702769 Nov 23 '11 at 17:48