首页新闻找找看学习计划

如何在Entity Framework中隐式自动加载所有的子对象实体?

0
悬赏园豆:50 [待解决问题]
public class Department
{
public int Id {get; set;}
public string Name {get; set;}
}

public class Employee
{
public int Id {get; set;}
public string Name {get; set;}
    [Required]
public Department Department {get; set;}
}

现在要更新Employee中的Name属性,编写下面的代码:

using (var db = new DBContext())
{
var employee = db.Employees.Include("Department").First();
employee.Name = "New Name";
db.SaveChange();
}

如果没有显式调用 Include("Department"),就会引发DbEntityValidationException异常。

如果以后有扩展的需要,Employee类增加了额外实体属性,例如:

public class Employee
{
public int Id {get; set;}
public string Name {get; set;}
[Required]
public Department Department {get; set;}
[Required]
public Grade Grade {get; set;}
}

就必须修改上面的保存代码,加入 Include("Grade") 。如果忘记了,编译过程也不能及时发现错误,只能在运行时引发异常。

我的问题是,如何不显式调用Include而自动隐式加载所有Required的实体属性,如上述的“Department”和“Grade”,这样以后扩充Employee类就不会有这样潜在的问题了。

谢谢~

jlzhou的主页 jlzhou | 初学一级 | 园豆:190
提问于:2012-03-09 10:39
< >
分享
所有回答(2)
0
public virtual Department Department {get; set;}

试试

奶茶爽歪歪 | 园豆:243 (菜鸟二级) | 2012-03-09 12:46

不行

支持(0) 反对(0) jlzhou | 园豆:190 (初学一级) | 2012-03-09 22:06

@jlzhou: 一楼的这个是启用Lazy Loading 为什么不行,因为什么原因? 另外,你也可以在使用这个导航属性之前检测它是否已经IsLoaded, 然后Explicit Loading, 比如这样:

                var entry = context.Entry(employee);
                if (!entry.Reference(e => e.Department).IsLoaded)
                {
                    entry.Reference(e => e.Department).Load();
                }

也是挺方便的,数据只有需要的时候,才到后台数据库去取,对吧?

支持(0) 反对(0) ChatinCode | 园豆:2272 (老鸟四级) | 2012-04-16 10:07
0

Entity Framework中没有提供这个特性,需要自己去实现。

参考内容:Entity framework auto eager load

dudu | 园豆:39108 (高人七级) | 2012-03-10 17:41

Is there a way to get entity objects to automatically pull all relevant data through the relationships instead of having having to .Include everything I want populated? I can't use lazy loading as this needs to be serialized to go over WCF. It would just be fantastic to have it auto populate the relevant collections.

正是我要问的问题,我找了半天也没找到答案,可惜了,谢谢dudu。 

支持(0) 反对(0) jlzhou | 园豆:190 (初学一级) | 2012-03-10 21:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册