[英]How to include all relations in entity framework 6?
Items = new ObservableCollection<CompanyContact>(
db.CompanyContacts
.Include(p => p.Facility)
.Include(p => p.Company)
.Include(p => p.Manager)
.OrderBy(s => s.Name)
.ToList<CompanyContact>()
);
有更优雅的方式来写吗? 我想在表格中包含所有关系。 像IncludeAll
这样的东西? 谢谢!
EF没有包含所有导航属性的方法。 如果您需要急切加载所有这些内容,除了要为要加载的每个导航属性调用所有包含外,别无选择。 稍微优雅的解决方案可能是使用以下扩展方法之一:
public static class IQueryableExtensions
{
public static IQueryable<TEntity> GetAllIncluding<TEntity>(this IQueryable<TEntity> queryable, params string[] includeProperties)
{
return includeProperties.Aggregate(queryable, (current, includeProperty) => current.Include(includeProperty));
}
public static IQueryable<TEntity> GetAllIncludingWithFunc<TEntity>(this IQueryable<TEntity> queryable, params Expression<Func<TEntity, object>>[] includeProperties)
{
return includeProperties.Aggregate(queryable, (current, includeProperty) => current.Include(includeProperty));
}
}
例如,使用第一种方法,您的查询将如下所示:
db.CompanyContacts.GetAllIncluding("Facility","Company", "Manager").OrderBy(s => s.Name).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.