簡體   English   中英

如何將 ThenInclude 實現到 EF Core 自定義規范中?

[英]How to implement ThenInclude into EF Core custom specification?

EF Core 3.1 我看過規范示例,並且想要實現 ThenInclude 模式。

public static class QuerySpecificationExtensions
{
    public static IQueryable<T> Specify<T>(this IQueryable<T> query, ISpecification<T> spec) where T : class
    {
        // fetch a Queryable that includes all expression-based includes
        var queryableResultWithIncludes = spec.Includes
            .Aggregate(query,
                (current, include) => current.Include(include));

        // modify the IQueryable to include any string-based include statements
        var secondaryResult = spec.IncludeStrings
            .Aggregate(queryableResultWithIncludes,
                (current, include) => current.Include(include));

        // return the result of the query using the specification's criteria expression
        return secondaryResult.Where(spec.Criteria);
    }
}

我可以將其添加到字符串中,例如“User.UserRole.Role”,但我想實現對象。 也許那里不可能?

Includes上述ISpecification<T>被聲明為

List<Expression<Func<T, object>>> Includes { get; }

問題是 EF Core Include / ThenInclude鏈不能用Expression<Func<T, object>> 此模式在 EF6 中使用,它支持包含表達式內的特殊語法 ( Select ) 來解析集合元素。 但是 EF Core 不支持開箱即用。

插入 EF Core 模式的最簡單、最自然的方法是更改​​定義如下:

List<Func<IQueryable<T>, IIncludableQueryable<T, object>>> Includes { get; }

為具有User屬性且UserRoles集合具有Role屬性的實體添加示例如下:

Includes.Add(q => q.Include(e => e.User).ThenInclude(e => e.UserRoles).ThenInclude(e => e.Role));

Specify方法實現的相應部分將是:

var queryableResultWithIncludes = spec.Includes
    .Aggregate(query,
        (current, include) => include(current));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM