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();
关于c# - 如何在 Entity Framework 6 中包含所有关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654044/