How to update entity navigation properties in the Entity Framework

In ASP.NET MVC 3 with the Entity Framework, I have a domain object that has a navigation property that references other objects, as follows:

public class Person { public String Name {get;set;} public Guid CompanyID{get;set;} [ForeignKey(CompanyID)] public virtual CompanyType Company{ get; set; } } 

When I create an instance of Person and try to add it to the database, DBContext stores the cache of this Person object and sends it to the database. So later in the life of the same instance of the context, when I try to access this object, the Company field is always null, since the navigation property has never been updated.

Is there a way to update the navigation property with what exists in the database?

Lazy loading is included.

+8
asp.net-mvc-3 entity-framework dbcontext ef-code-first navigation-properties
source share
1 answer

If lazy loading is enabled and you want to load the navigation property with lazy loading, you should create a proxy for the new Person , and not create it using new , for example:

 using (var context = new MyDbContext()) { var person = context.People.Create(); // creates a lazy loading proxy person.CompanyID = 123; context.People.Add(person); context.SaveChanges(); var company = person.Company; // lazy loading query happens here } 

Without lazy loading, you can use explicit loading:

 using (var context = new MyDbContext()) { var person = new Person(); person.CompanyID = 123; context.People.Add(person); context.SaveChanges(); context.Entry(person).Reference(p => p.Company).Load(); // explicit loading var company = person.Company; // no query anymore, Company is already loaded } 
+11
source share

All Articles