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类就不会有这样潜在的问题了。
谢谢~
public virtual Department Department {get; set;}
试试
不行
@jlzhou: 一楼的这个是启用Lazy Loading 为什么不行,因为什么原因? 另外,你也可以在使用这个导航属性之前检测它是否已经IsLoaded, 然后Explicit Loading, 比如这样:
var entry = context.Entry(employee); if (!entry.Reference(e => e.Department).IsLoaded) { entry.Reference(e => e.Department).Load(); }
也是挺方便的,数据只有需要的时候,才到后台数据库去取,对吧?
Entity Framework中没有提供这个特性,需要自己去实现。
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。