简体   繁体   English

实体框架核心,具有包含导航属性的通用存储库方法

[英]entity framework core, generic repository method with inclusion navigation properties

I want to create a universal data access layer through a business logic project, The business logic layer must interact with the DAL layer in which I have a repository. 我想通过业务逻辑项目创建通用数据访问层。业务逻辑层必须与我拥有存储库的DAL层进行交互。 I want to have a short-lived data context and all the repository methods returning IEnumerable and not IQueryable. 我想拥有一个短暂的数据上下文,并且所有存储库方法都返回IEnumerable而不是IQueryable。 Prompt on an example of method GetAll how I can extract the connected data through ThenInclude or Select to dependent tables. 提示方法GetAll的示例,我如何通过ThenInclude或Select提取依赖表中的连接数据。

public class GenericDataRepository<T> : IGenericDataRepository<T> where T : class
{
    public virtual IList<T> GetAll(params Expression<Func<T, object>>[] navigationProperties)
    {

        List<T> list;
        using (var context = new Context())
        {
            IQueryable<T> dbQuery = context.Set<T>();

            //Apply eager loading
            foreach (Expression<Func<T, object>> navigationProperty in navigationProperties)
                dbQuery = dbQuery.Include<T, object>(navigationProperty);

            list = dbQuery
                .AsNoTracking()
                .ToList<T>();
        }
        return list;
    }

} }

ThenInclude(prop2=>prop2.i)? 然后包含(prop2 => prop2.i)?

dbQuery.Include(navigationProperty).ThenInclude(prop2=>prop2.i) dbQuery.Include(navigationProperty).ThenInclude(prop2 => prop2.i)

This is actually bad design. 这实际上是不好的设计。 You don't want to do this. 您不想这样做。 If you want to abstract your data access layer, then do so completely. 如果要抽象数据访问层,请完全这样做。 Create a library that provides an API for your application, which returns exactly what you need, no more and no less. 创建一个为您的应用程序提供API的库,此库将准确无误地返回您所需的内容。 If you're going to still allow arbitrary querying, then just utilize your context directly, as you're not actually buying yourself anything other than an additional layer to maintain, with no real benefit. 如果您仍然允许任意查询,则直接使用您的上下文,因为您实际上除了购买要维护的其他层之外没有购买任何东西,没有任何实际好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM