Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In <a href="/questions/tagged/entity-framework-5" class="post-tag" title="show questions tagged &#39;entity-framework-5&#39;" rel="tag">entity-framework-5</a>, this is insanely easy with the <a href="http://msdn.microsoft.com/en-us/library/system.data.entity.dbextensions.asnotracking(v=vs.103).aspx">DbExtensions.AsNotracking()</a>. </p> <blockquote> <p>Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext.</p> </blockquote> <p>This appears to be the case for all objects in the object graph.</p> <p>You just have to really understand your graph and what you do and don't want inserted/duplicated into the DB.</p> <p>Lets assume we have objects like:</p> <pre><code>public class Person { public int ID { get; set; } public string Name { get; set; } public virtual ICollection&lt;Address&gt; Addresses { get; set; } } public class Address { public int ID { get; set; } public AddressLine { get; set; } public int StateID { get; set; } public ICollection&lt;State&gt; { get; set; } } </code></pre> <p>So in order to Duplicate a person, I need to duplicate the addresses, but I don't want to duplicate the States.</p> <pre><code>var person = this._context.Persons .Include(i =&gt; i.Addresses) .AsNoTracking() .First(); // if this is a Guid, just do Guid.NewGuid(); // setting IDs to zero(0) assume the database is using an Identity Column person.ID = 0; foreach (var address in person.Addresses) { address.ID = 0; } this._context.Persons.Add(person); this._context.SaveChanges(); </code></pre> <p>If you then wanted to then reuse those same objects again to insert a third duplicate, you'd either run the query again (with AsNoTracking()) or detach the objects (example):</p> <pre><code>dbContext.Entry(person).State = EntityState.Detached; person.ID = 0; foreach (var address in person.Addresses) { dbContext.Entry(address).State = EntityState.Detached; address.ID = 0; } this._context.Persons.Add(person); this._context.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