Entity Framework - adding new items via a navigation property

Posted by Robert on Stack Overflow See other posts from Stack Overflow or by Robert
Published on 2010-06-12T10:21:23Z Indexed on 2010/06/12 10:22 UTC
Read the original article Hit count: 1197

I have come across what appears to be very peculiar behaviour using entity framework 4.0.

I have a User entity, which has a Company (A Company has many Users).

If I do this, everything works as expected and I get a nice shiny new user in the database:

var company = _model.Companies.First();
company.Users.Add(new User(1, "John", "Smith"));
_model.SaveChanges();

However, if I do this, then I get nothing new in the database, and no exceptions thrown:

var existingUser = _model.Users.First();
var company = existingUser.Company;
company.Users.Add(new User(1, "John", "Smith"));
_model.SaveChanges();

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.

Can someone tell me if this is expected behaviour, or if there is something I can do to make it so that it is?

Thanks!

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about navigation