Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework: Shouldn't attaching the following entity throw an exception?
    text
    copied!<p>As far as I can tell, <code>EntityCollection.Attach</code> and <code>EntityReference.Attach</code> can only create relationships that already exists in the database. In other words, if <code>Address.EmployeeID == Employee.EmployeeID</code>, then the following code will work:</p> <pre><code> Employee employee = context.Employees.First(); Address address = context.Addresses.First(); employee.Addresses.Attach(address); </code></pre> <p>But if <code>Address.EmployeeID != Employee.EmployeeID</code>, then the code will throw an exception:</p> <pre><code> Employee employee = context.Employees.First(); Address address = context.Addresses.First(); employee.Addresses.Attach(address); // System.InvalidOperationException: A // referential integrity constraint // violation occurred </code></pre> <p>But according to a code example taken from the following <a href="https://stackoverflow.com/questions/3920111/entity-framework-4-addobject-vs-attach">thread</a>, <code>EntityCollection.Attach</code> and <code>EntityReference.Attach</code> can also be used to create a relationship that doesn't exist in a DB:</p> <pre><code>var existingPerson = ctx.Persons.SingleOrDefault(p =&gt; p.Name = "Joe Bloggs" }; var myAddress = ctx.Addresses.First(a =&gt; a.PersonID != existingPerson.PersonID); existingPerson.Addresses.Attach(myAddress); // OR: myAddress.PersonReference.Attach(existingPerson) ctx.SaveChanges(); </code></pre> <p>So am I correct in assuming that <code>EntityCollection.Attach</code> and <code>EntityReference.Attach</code> can only create relationships that already exists in the database, and as such code example taken from the other thread should throw an exception?</p> <p>Thank you </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload