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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句