[英]How to implement ThenInclude into EF Core custom specification?
EF Core 3.1 I have seen Specification example, and want to implement ThenInclude pattern. 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);
}
}
I can add this into string for example "User.UserRole.Role", but I want to implement object.我可以将其添加到字符串中,例如“User.UserRole.Role”,但我想实现对象。 Maybe there it is not possible?也许那里不可能?
Includes
member of the aforementioned ISpecification<T>
is declared as Includes
上述ISpecification<T>
被声明为
List<Expression<Func<T, object>>> Includes { get; }
The problem is that EF Core Include
/ ThenInclude
chain cannot be represented with Expression<Func<T, object>>
.问题是 EF Core Include
/ ThenInclude
链不能用Expression<Func<T, object>>
。 This pattern was used in EF6 which supported a special syntax ( Select
) inside the include expression to resolve collection element.此模式在 EF6 中使用,它支持包含表达式内的特殊语法 ( Select
) 来解析集合元素。 But EF Core does not support that out of the box.但是 EF Core 不支持开箱即用。
The easiest and most natural way to plug EF Core pattern is to change the definition as follows:插入 EF Core 模式的最简单、最自然的方法是更改定义如下:
List<Func<IQueryable<T>, IIncludableQueryable<T, object>>> Includes { get; }
Adding the sample for entity having User
property having UserRoles
collection having Role
property would be like this:为具有User
属性且UserRoles
集合具有Role
属性的实体添加示例如下:
Includes.Add(q => q.Include(e => e.User).ThenInclude(e => e.UserRoles).ThenInclude(e => e.Role));
And the corresponding part of the Specify
method implementation would be: Specify
方法实现的相应部分将是:
var queryableResultWithIncludes = spec.Includes
.Aggregate(query,
(current, include) => include(current));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.