Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update an entity's navigation properties in Entity Framework

In ASP .NET MVC 3 with Entity Framework, I have a domain object which has a navigation property referencing another 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, the DBContext keeps a cache of this entity 'Person' and sends it to the database. So later on in the lifetime of the same context instance, when I try to access this entity, the Company field is always null since the navigation property never got updated.

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

Lazy loading is turned on.

like image 976
daniely Avatar asked May 10 '12 21:05

daniely


People also ask

How do I update items in Entity Framework?

Update Objects in Entity Framework 4.0First retrieve an instance of the entity from the EntitySet<T> (in our case ObjectSet<Customer>), then edit the properties of the Entity and finally call SaveChanges() on the context.

What is Navigation property in asp net?

A navigation property is an optional property on an entity type that allows for navigation from one end of an association to the other end. Unlike other properties, navigation properties do not carry data.


1 Answers

If lazy loading is turned on and you want to load the navigation property with lazy loading you must create a proxy of a new Person, not instantiate it with new, like so:

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
}
like image 197
Slauma Avatar answered Sep 21 '22 04:09

Slauma