【问题标题】:Ef core include for many-to-many in the generic repositoryEf core 在通用存储库中包含多对多
【发布时间】:2020-11-10 19:52:35
【问题描述】:

我在数据库中有多对多的关系。 GetAll 方法的 EF Core 中预加载的典型实现是:

    dbContext
    .DbSet<Book>
    .Include(e => e.BooksAuthors)
    .ThenInclude(ba => ba.Author)

但在通用存储库的情况下,我将 params Expression&lt;Func&lt;T, object&gt;&gt;[] includes 作为参数传递给 GetAll。

但问题是,在

的帮助下
public static IQueryable<T> IncludeMultiple<T>(
   this IQueryable<T> query,
   params Expression<Func<T, object>>[] includes)
            where T : class
        {
            if (includes != null)
            {
                query = includes.Aggregate(query,
                    (current, include) => current.Include(include));
            }

            return query;
        }

我只能加载 BooksAuthors,不能加载下一层嵌套。如何将 ThenInclude 作为参数传递?

【问题讨论】:

  • 不要使用“通用”存储库anti模式。 DbSet 已经是一个存储库,一个 DbContext 已经是一个工作单元。 DbContext 既不是连接也不是整个数据库的模型。 不要直接调用DbSet&lt;&gt;(),你需要做的就是正确配置你的DbContext并让它完成它的工作。
  • 阅读 Gunnar Peipman 的 No need for repositories and unit of work with Entity Framework Core 以了解“通用”存储库的糟糕程度以及 Oren Eini 的 Repository is the new Singleton。 Oren Eini 当时是 NHibernate 的维护者。 DbContext 的实体 DDD 有界上下文的聚合根。 DbContext 应该匹配 DDD 有界上下文。

标签: c# ef-core-3.1


【解决方案1】:

可以使用字符串版本的include

public static IQueryable<T> IncludeMultiple<T>(
   this IQueryable<T> query,
   params string[] includes)
            where T : class
        {
            if (includes != null)
            {
                query = includes.Aggregate(query,
                    (current, include) => current.Include(include));
            }

            return query;
        }

你的包含将是

dbContext.DbSet<Book>.IncludeMultiple("BooksAuthors.Author")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-24
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多