简体   繁体   English

实体框架延迟加载和更新模型

[英]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. 当我从数据库中加载模型B时,我仅更改名称并更新它,就会出现以下错误:ObjectA字段为必填字段。

I think this is because ObjectA is lazy loaded. 我认为这是因为ObjectA是延迟加载的。 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. 但是,当我从数据库中加载B后添加断点,然后在变量浏览器中查看B的内容时,将加载A,并且更新B不会出错。

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. 正在发生的事情是,当你在一个断点停止,并检查属性的值ObjectA的内部objB ,你是明确的加载性能。

In the GetObjBByIdUsingLINQ(id) method you should use an Include to load your property, for example: GetObjBByIdUsingLINQ(id)方法中,应使用Include来加载属性,例如:

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 . 您可以在此博客文章中阅读有关使用相关实体的全部信息: 在EF 4.1第6部分:加载相关实体中使用DbContext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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