我使用投影将实体类映射到使用Entity Framework Core的DTO。但是,投影会将ToList添加到子集合属性中,这会使查询速度大大降低。
公司实体:
public class Company
{
public Company()
{
Employees = new List<CompanyEmployee>();
}
public string Address { get; set; }
public virtual ICollection<CompanyEmployee> Employees { get; set; }
...
}
公司DTO:
public class CompanyDTO
{
public CompanyDTO()
{
CompanyEmployees = new List<EmployeeDTO>();
}
public string Address { get; set; }
public List<EmployeeDTO> CompanyEmployees { get; set; }
...
}
配置:
CreateMap<Company, CompanyDTO>()
.ForMember(c => c.CompanyEmployees, a => a.MapFrom(src => src.Employees));
CreateMap<CompanyEmployee, EmployeeDTO>();
查询:
UnitOfWork.Repository<Company>()
.ProjectTo<CompanyDTO>(AutoMapper.Mapper.Configuration)
.Take(10)
.ToList();
在Expression
之后使用ProjectTo
属性检查生成的查询会产生以下结果:
Company.AsNoTracking()
.Select(dtoCompany => new CompanyDTO()
{
Address = dtoCompany.Address,
...
CompanyEmployees = dtoCompany.Employees.Select(dtoCompanyEmployee => new EmployeeDTO()
{
CreatedDate = dtoCompanyEmployee.CreatedDate,
...
}).ToList() // WHY??????
})
该ToList
调用导致对每个实体运行选择查询,这不是我想要的。我测试了没有该ToList
的查询(通过手动复制表达式并运行它),并且一切正常。如何防止AutoMapper添加该呼叫?我尝试将DTO中的List
类型更改为IEnumerable
,但没有任何更改。
答案 0 :(得分:3)
让我们忽略ToList
调用的EF核心影响,而专注于AutoMapper ProjectTo
。
该行为被硬编码在EnumerableExpressionBinder
类中:
expression = Expression.Call(typeof(Enumerable), propertyMap.DestinationPropertyType.IsArray ? "ToArray" : "ToList", new[] { destinationListType }, expression);
此类在AutoMapper QueryableExtensions处理管道的一部分中,负责将可枚举的源转换为可枚举的目标。正如我们所看到的,它总是发出ToArray
或ToList
。
实际上,当目标成员类型为ICollection<T>
或IList<T>
时,需要进行ToList
调用,因为否则表达式将无法编译。但是,当目标成员类型为IEnumerable<T>
时,这是任意的。
因此,如果您想摆脱上述情况下的这种行为,可以在IExpressionBinder
之前注入自定义EnumerableExpressionBinder
({ IsMatch
这样返回true
)(
namespace AutoMapper
{
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper.Configuration.Internal;
using AutoMapper.Mappers.Internal;
using AutoMapper.QueryableExtensions;
using AutoMapper.QueryableExtensions.Impl;
public class GenericEnumerableExpressionBinder : IExpressionBinder
{
public bool IsMatch(PropertyMap propertyMap, TypeMap propertyTypeMap, ExpressionResolutionResult result) =>
propertyMap.DestinationPropertyType.IsGenericType &&
propertyMap.DestinationPropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>) &&
PrimitiveHelper.IsEnumerableType(propertyMap.SourceType);
public MemberAssignment Build(IConfigurationProvider configuration, PropertyMap propertyMap, TypeMap propertyTypeMap, ExpressionRequest request, ExpressionResolutionResult result, IDictionary<ExpressionRequest, int> typePairCount, LetPropertyMaps letPropertyMaps)
=> BindEnumerableExpression(configuration, propertyMap, request, result, typePairCount, letPropertyMaps);
private static MemberAssignment BindEnumerableExpression(IConfigurationProvider configuration, PropertyMap propertyMap, ExpressionRequest request, ExpressionResolutionResult result, IDictionary<ExpressionRequest, int> typePairCount, LetPropertyMaps letPropertyMaps)
{
var expression = result.ResolutionExpression;
if (propertyMap.DestinationPropertyType != expression.Type)
{
var destinationListType = ElementTypeHelper.GetElementType(propertyMap.DestinationPropertyType);
var sourceListType = ElementTypeHelper.GetElementType(propertyMap.SourceType);
var listTypePair = new ExpressionRequest(sourceListType, destinationListType, request.MembersToExpand, request);
var transformedExpressions = configuration.ExpressionBuilder.CreateMapExpression(listTypePair, typePairCount, letPropertyMaps.New());
if (transformedExpressions == null) return null;
expression = transformedExpressions.Aggregate(expression, (source, lambda) => Select(source, lambda));
}
return Expression.Bind(propertyMap.DestinationProperty, expression);
}
private static Expression Select(Expression source, LambdaExpression lambda)
{
return Expression.Call(typeof(Enumerable), "Select", new[] { lambda.Parameters[0].Type, lambda.ReturnType }, source, lambda);
}
public static void InsertTo(List<IExpressionBinder> binders) =>
binders.Insert(binders.FindIndex(b => b is EnumerableExpressionBinder), new GenericEnumerableExpressionBinder());
}
}
这基本上是EnumerableExpressionBinder
的修改后的副本,具有不同的IsMatch
检查并删除了ToList
调用发出代码。
现在,如果将其注入到AutoMapper配置中
:Mapper.Initialize(cfg =>
{
GenericEnumerableExpressionBinder.InsertTo(cfg.Advanced.QueryableBinders);
// ...
});
,然后将您的DTO集合类型设为IEnumerable<T>
:
public IEnumerable<EmployeeDTO> CompanyEmployees { get; set; }
ProjectTo
将使用Select
生成表达式,但不包含ToList
。