Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can't you attach new objects to tracked objects using navigation references?
    primarykey
    data
    text
    <p>In short, why does this fail (<code>myChildObject</code> is <strong>not</strong> added to the database). <em>Note that it works with ObjectContext</em>:</p> <pre><code>using (var db = new dbEntities()) { var myParentObject = db.parentObjects.First(); // this definitely exists in the db // this **should** attach myChildObject to the context, // and therefore add it to the db on .SaveChanges() - it doesn't! var myChildObject = new childObject(){ parentObject = myParentObject }; db.SaveChanges(); } </code></pre> <p><a href="http://msdn.microsoft.com/en-US/data/jj592676" rel="nofollow">This MSDN Blog Post</a> says </p> <blockquote> <p>You can add a new entity to the context by hooking it up to another entity that is already being tracked. This could be by adding the new entity to the collection navigation property of another entity or by setting a reference navigation property of another entity to point to the new entity.</p> </blockquote> <p>Surely the above code should work because <code>myChildObject</code> references <code>myParentObject</code> which is a tracked object. EF should be smart enough to figure out that it needs adding into the <code>childObjects</code> collection. It worked fine when I was using ObjectContext and now I'm finding that I need to rewrite all of my code to get it to work with dbContext.</p> <p>To get it to work I have to rewrite it like this:</p> <pre><code>using (var db = new dbEntities()) { var myParentObject = db.parentObjects.First(); // this definitely exists in the db var myChildObject = new childObject(); myParentObject.childObjects.Add(myChildObject); db.SaveChanges(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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