c# - 如何在 Entity Framework 6 中包含所有关系?

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

最佳答案

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/

相关文章:

java - C# 中的 COBOL 到 Java 转换器

c# - 显示 MvxDialogFragment 的简单方法是什么?

c# - 预处理器指令

c# - EntityFramework - 选择具有自定义属性投影的实体

c# - LINQ 选择非空

c# - ModelState.IsValid 忽略 [Required] 属性

c# - 查询本地组

c# - 将项目添加到 Listview 控件

entity-framework - EF 4.0 实体在插入后不拾取新值(插入后选择实体)

c# - EF 多重关系