Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework - adding new items via a navigation property
    primarykey
    data
    text
    <p>I have come across what appears to be very peculiar behaviour using entity framework 4.0.</p> <p>I have a User entity, which has a Company (A Company has many Users).</p> <p>If I do this, everything works as expected and I get a nice shiny new user in the database:</p> <pre><code>var company = _model.Companies.First(); company.Users.Add(new User(1, "John", "Smith")); _model.SaveChanges(); </code></pre> <p>However, if I do this, then I get nothing new in the database, and no exceptions thrown:</p> <pre><code>var existingUser = _model.Users.First(); var company = existingUser.Company; company.Users.Add(new User(1, "John", "Smith")); _model.SaveChanges(); </code></pre> <p>So it appears that if I add a User to the Company that is pulled directly from the model, then everything works fine. However if the User is added to a Company that is pulled as a navigation property of another object, then it doesn't work.</p> <p>Can someone tell me if this is expected behaviour, or if there is something I can do to make it so that it is?</p> <p>Thanks!</p> <h2>Edit</h2> <p>To clarify what I mean by "it doesn't work";</p> <ul> <li>Stepping through the code shows the execution pointer going past all lines without throwing an exception.</li> <li>No new row is added to the database</li> <li>If I check company.Users in quick watch, the new user has indeed been added to the company - it's just not being saved to the database.</li> </ul> <p>I've done a little more playing, and it seems that if I do this, I get an exception:</p> <pre><code>var existingUser = _model.Users.First(); var company = existingUser.Company; _model.ObjectStateManager.GetObjectStateEntry(company); </code></pre> <p>The exception is:</p> <blockquote> <p>System.InvalidOperationException: The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'ABC.DEF.Company'.</p> </blockquote> <p>Doing that for the first (working) scenario provides me with an ObjectStateEntry back without throwing an exception.</p>
    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.
    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