简体   繁体   English

EF Core 2.0 包括具有动态查询的嵌套实体

[英]EF Core 2.0 include nested entities with dynamic query

I am using System.Linq.Dynamic.Core;我正在使用System.Linq.Dynamic.Core; and the following extension method to access a DbSet dynamically by name and generate queries from strings.以及以下扩展方法,用于按名称动态访问 DbSet 并从字符串生成查询。

This is extesion method:这是扩展方法:

namespace Microsoft.EntityFrameworkCore
{
    public static partial class CustomExtensions
    {
        public static IQueryable Query(this DbContext context, string entityName) =>
            context.Query(context.Model.FindEntityType(entityName).ClrType);

        public static IQueryable Query(this DbContext context, Type entityType) =>
            (IQueryable)((IDbSetCache)context).GetOrAddSet(context.GetDependencies().SetSource, entityType);
    }
}

This is how I access the DbSet:这是我访问 DbSet 的方式:

IQueryable<T> dbSet = (IQueryable<T>)_db.Query(entityName);

This works fine, I can build a query and then create a list but none of the nested entities load.这工作正常,我可以构建一个查询,然后创建一个列表,但没有任何嵌套实体加载。 It seems IQueryable doesn't have a definition for Include() .似乎IQueryable没有Include()的定义。 I can see include method if I access db context directly in normal fashion but not using this dynamic method.如果我以正常方式直接访问数据库上下文但不使用此动态方法,我可以看到包含方法。

How do I include nested entities using dynamic method?如何使用动态方法包含嵌套实体?

First of all You are using GetOrAddSet of IDbSetCache首先您使用的是IDbSetCache GetOrAddSet

 public interface IDbSetCache

// // Summary: // This API supports the Entity Framework Core infrastructure and is not intended // to be used directly from your code. // // 摘要: // 此 API 支持 Entity Framework Core 基础结构,不打算直接从您的代码中使用 //。 This API may change or be removed in future此 API 将来可能会更改或删除

Include is method of IQueryable<TEntity> in class EntityFrameworkQueryableExtensions of Microsoft.EntityFrameworkCore , not for IQueryable . IncludeMicrosoft.EntityFrameworkCoreEntityFrameworkQueryableExtensions中的IQueryable<TEntity>方法,不适用于IQueryable Your function returns IQueryable您的函数返回IQueryable

I would recommend you to create extention method like below,我建议您创建如下扩展方法,

        public static IQueryable<T> MyQuery<T>(this DbContext context)
            where T : class
        {
            return context.Set<T>().AsQueryable();
        }

And you can consume by,你可以消费,

  var result = _dbContext.MyQuery<Employee>().Include("Department");

For Dynamic include,对于动态包含,

    /// <summary>
    /// Query with dynamic Include
    /// </summary>
    /// <typeparam name="T">Entity</typeparam>
    /// <param name="context">dbContext</param>
    /// <param name="includeProperties">includeProperties with ; delimiters</param>
    /// <returns>Constructed query with include properties</returns>
    public static IQueryable<T> MyQueryWithDynamicInclude<T>(this DbContext context, string includeProperties)
       where T : class
    {            
        string[] includes = includeProperties.Split(';');
        var query = context.Set<T>().AsQueryable();

        foreach (string include in includes)
            query = query.Include(include);

        return query;
    }

I have a piece code for this problem.我有一个解决这个问题的代码。 I use Expression tree.我使用表达式树。

My entity model like as below:我的实体模型如下所示:

public class PortfolioTechnology
{
    public int PortfolioId { get; set; }
    public Portfolio Portfolio { get; set; }

    public int TechnologyId { get; set; }
    public Technology Technology { get; set; }
}

My main code like as below:我的主要代码如下:

public SharpListResponse<PortfolioTechnology> GetAll(
    Expression<Func<PortfolioTechnology, bool>> predicate,
    params Expression<Func<PortfolioTechnology,object>>[] includes)
{
    var query = _dbContext.PortfolioTechnology.AsQueryable();

    foreach (var include in includes)
    {
        var memberExpression = include.Body as MemberExpression;

        if (memberExpression != null)
            query = query.Include(memberExpression.Member.Name);
    }

    var result = query.Where(predicate).ToList();

    return new SharpListResponse<PortfolioTechnology>(result);
}

And usage this method like as below:并使用此方法如下:

var list = _unitOfWork.PortfolioTechnologyRepository.GetAll(x => x.PortfolioId == id, 
                                                            y => y.Technology);

If you want include multiple entities for example include Portfolio and Technology entities, your code like as below:如果您想包含多个实体,例如包含投资组合和技术实体,您的代码如下:

 var list = _unitOfWork.PortfolioTechnologyRepository.GetAll(x => x.PortfolioId == id, 
                                                             y => y.Technology,
                                                             x => x.Portfolio);

Note: SharpListResponse is wrapper class.注意: SharpListResponse是包装类。 Code is working without it代码在没有它的情况下工作

More details for SharpListResponse : https://www.nuget.org/packages/SharpRequestResponseWrapper/ SharpListResponse 的更多详细信息: https ://www.nuget.org/packages/SharpRequestResponseWrapper/

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

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