ASP.Net MVC.如何始终在实体框架查询中包含相关数据
本文关键字:查询 包含相 数据 框架 实体 MVC Net 何始终 ASP | 更新日期: 2023-09-27 18:00:03
使用Entity框架选择关系表时,我们必须手动在查询中"包含"相关数据,例如:
MyEntity entity = db.MyEntities
.Include(e => e.related_1)
.Include(e => e.related_2)
.FirstOrDefault(e => e.Id == id);
否则entity.related_1或entity.Rrelated_2将为空。
我想知道是否有一种方法可以在选择之前设置预包含关系,而无需每次都选择相关数据。例如:
db.preInclude(???) // not a real method.
someOtherCode(...)
MyEntity entity_1 = db.MyEntities.Find(id_1);
MyEntity entity_2 = db.MyEntities.Find(id_2);
MyEntity entity_3 = db.MyEntities.Find(id_3);
使您的相关实体成为虚拟的,以便启用Lazy加载,这样,您就不需要显式调用Include,当您引用此虚拟相关实体时,它将从数据库中检索
创建一个返回所需查询的函数,然后执行它:
public IQueryable getTheEntity(DbContext database) {
var query = from e in database.MainEntity.Include("SubEntity1.Another").Include("SubEntity2");
return query;
}
然后在需要完整模型时调用该函数:
using (MyDbContext database = new MyDbContext()) {
var result = (from e in getTheEntity(database) where ...).FirstOrDefault();
}
您甚至可以将getTheEntity(...)
作为DbContext类的扩展,这样调用它就不那么冗长了:
var result = (from e in database.getTheEntity() where ...).ToList();