如何在实体框架6中包含所有关系?

时间:2015-02-22 03:07:57

标签: c# entity-framework

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这样的东西? 谢谢!

1 个答案:

答案 0 :(得分:3)

EF doen没有包含所有导航属性的方法。如果您需要急切加载所有这些内容,除了要为要加载的每个导航属性调用所有包含外,别无选择。稍微优雅的解决方案可能是使用以下扩展方法之一:

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();