Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.addobject.aspx" rel="noreferrer"><strong>ObjectContext.AddObject</strong></a> and <strong><a href="http://msdn.microsoft.com/en-us/library/dd487277.aspx" rel="noreferrer">ObjectSet.AddObject</a></strong>: <br> The <em>AddObject</em> method is for adding newly created objects that do <strong><em>not</em></strong> exist in the database. The entity will get an automatically generated temporary <em>EntityKey</em> and its EntityState will be set to <em>Added</em>. When SaveChanges is called, it will be clear to the EF that this entity needs to be inserted into the database. <br></p> <p><strong><a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attach.aspx" rel="noreferrer">ObjectContext.Attach</a></strong> and <a href="http://msdn.microsoft.com/en-us/library/dd487214.aspx" rel="noreferrer"><strong>ObjectSet.Attach</strong></a>: <br> On the other hand, <em>Attach</em> is used for entities that already <strong><em>exist</em></strong> in the database. Rather than setting the EntityState to Added, Attach results in an <em>Unchanged</em> EntityState, which means it has not changed since it was attached to the context. Objects that you are attaching are assumed to exist in the database. If you modify the objects after they’ve been attached, when you call SaveChanges the value of the EntityKey is used to update (or delete) the appropriate row by finding its matching ID in the db table. <br><br> Furthermore, using the Attach method, you can define relationships between entities that already exist in the ObjectContext but that have <strong><em>not</em></strong> been connected automatically. Basically the main purpose of Attach, is to connect entities that are already attached to the ObjectContext and are <em>not</em> new so you cannot use Attach to attach entities whose EntityState is Added. You have to use <em>Add()</em> in this case. <br><br> For example, let's assume your Person entity has a navigation property named <em>Addresses</em> which is a collection of <em>Address</em> entity. Let's say you have read both Objects from context, but they are not related to each other and you want to make it so:</p> <pre><code>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(); </code></pre>
 

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