Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 22nd, 2012  |  syntax: None  |  size: 1.10 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Entity Framework: Shouldn't attaching the following entity throw an exception?
  2. Employee employee = context.Employees.First();
  3.         Address address = context.Addresses.First();
  4.         employee.Addresses.Attach(address);
  5.        
  6. Employee employee = context.Employees.First();
  7.         Address address = context.Addresses.First();
  8.         employee.Addresses.Attach(address); // System.InvalidOperationException: A
  9.                                             // referential integrity constraint
  10.                                             // violation occurred
  11.        
  12. var existingPerson = ctx.Persons.SingleOrDefault(p => p.Name = "Joe Bloggs" };
  13. var myAddress = ctx.Addresses.First(a => a.PersonID != existingPerson.PersonID);
  14. existingPerson.Addresses.Attach(myAddress);
  15. // OR:
  16. myAddress.PersonReference.Attach(existingPerson)
  17. ctx.SaveChanges();
  18.        
  19. var existingPerson = ctx.Persons.SingleOrDefault(p => p.Name = "Joe Bloggs" };
  20. var myAddress = ctx.Addresses.First(a => a.PersonID == existingPerson.PersonID);
  21. existingPerson.Addresses.Attach(myAddress);
  22. // OR:
  23. myAddress.PersonReference.Attach(existingPerson)
  24. ctx.SaveChanges();