简体   繁体   中英

Entity Framework lazy loading and updating model

I have defined some models like this (Entity Framework Code-First):

public class A
{
  public int Id { get; set; }
  public int Name { get; set; }
}

public class B
{
  public int Id { get; set; }
  public int Name { get; set; }
  public virtual A ObjectA { get; set; }
}

// model update sample code
public void UpdateModel(int id, string name)
{
  B objB = GetObjBByIdUsingLINQ(id); // this function gets the object using LINQ
  if (objB != null) // <-- if you do a breakpoint here and inspect objB, objB.A != null
  {
    objB.Name = name;
    dbContext.Entry(objB).State = EntityState.Modified;
    dbContext.SaveChanges(); // <-- DbEntityValidationException here because objB.A == null
  }
}

When I Load a model B from the database, and I only change the Name and I update it I get the following error: The ObjectA field is required.

I think this is because ObjectA is lazy loaded. However, when I add a breakpoint after I loaded B from the database, and then I view the contents of B in the variable explorer, A will be loaded, and updating B doesn't give an error.

Any ideas how to solve this problem?

What is happening is that when you stop in a breakpoint and inspect the value of the property ObjectA inside your objB , you are explicitly loading the property.

In the GetObjBByIdUsingLINQ(id) method you should use an Include to load your property, for example:

var objB = from b in dbContext.Bs.Include("ObjectA")
           where b.Id == id
           select b;

Or you can load the property explicitly, instead:

dbContext.Entry(objB).Reference("ObjectA").Load();

You should note that the first option will hit the database only once. In the second option, you will hit the database twice. That should be taken into account depending on your specific case.
You can read all about working with related entities in this blog post: Using DbContext in EF 4.1 Part 6: Loading Related Entities .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM