AutoMapper ForMember映射中的重用代码

问题描述 投票:0回答:1

我正在研究Entity Framework CoreAutoMapper(版本9)的解决方案。从我的实体类到DTO的映射是通过投影完成的。

var dto = await context.Companies
    .ProjectTo<MyDto>(config, new { departmentName = "Sales" });

在映射中,我选择某个部门。

public class MyProfile : Profile
{
    public MyProfile()
    {
        string departmentName = null;

        CreateMap<Company, MyDto>()
            .ForMember(m => m.DepartmentLocation, opt => opt.MapFrom(src =>
                src.Divisions.SelectMany(dv => 
                    dv.Departments.Where(d => d.Name == departmentName)
                )
                .Single().Location));
    }
}

是否可以将代码移动到概要文件类中的另一个部门(专用)方法中以选择部门?


DTO其他成员的映射中也将需要此代码。

我曾尝试将代码移至另一种方法,但是随后部门的公司集合没有被填充。可能是因为EF无法将方法转换为SQL。我还尝试将方法重写为一个返回部门的Func表达式,但是后来我无法直接使用结果访问映射中的部门属性。

public class MyProfile : Profile
{
  public MyProfile()
    {
        string departmentName = null;

        CreateMap<Company, MyDto>()
            .ForMember(m => m.DepartmentLocation, opt => opt.MapFrom(src =>
                SelectDepartment(src, departmentName).Location)
            );
    }

    private Department SelectDepartment(Company company, string departmentName)
    {
        var department = company.Divisions
            .SelectMany(Departments.Where(d => d.Name == departmentName)
            .First();

        if (department == null)
            throw new AutoMapperMappingException($"Department '{departmentName}' not found!");

        return department;
    }
}

有什么建议吗?

c# entity-framework-core automapper
1个回答
0
投票

这是为您提供解决方案的一半,但是无论如何我都会发布它。您可以通过创建提供表达式的方法来完成映射。问题是-如果找不到拟合部,如何引发异常,因为您不能在表达式中引发异常。我建议在映射之后引发异常,因为无论如何您都必须查询数据。

public class MyMappingProfile : Profile
{
    public MyMappingProfile()
    {
        string departmentName = "Foo";

        CreateMap<Company, MyDto>()
            .ForMember(m => m.DepartmentLocation, opt => opt.MapFrom(SelectDepartment(departmentName)));
    }

    private Expression<Func<Company, string>> SelectDepartment(string departmentName)
        => (company) => company.Divisions
            .SelectMany(division => division.Departments)
            .Where(department => department.Name == departmentName)
            .FirstOrDefault()
            .Location;
}

EF Core将生成不错的查询:

SELECT(
    SELECT TOP(1) [d0].[Name]
    FROM [Division] AS[d]
          INNER JOIN [Department] AS [d0] ON [d].[Id] = [d0].[DivisionId]
    WHERE ([c].[Id] = [d].[CompanyId]) 
        AND ([d0].[Name] = @__departmentName_0)) 
    AS [DepartmentLocation]
FROM [Company] AS[c]

用法:

var result = dbContext
    .Set<Company>()
    .ProjectTo<MyDto>(mapperConfiguration)
    .ToList();

result.ForEach(myDto =>
{
    if (myDto.DepartmentLocation == null)
    {
        throw new AutoMapperMappingException("Department was not found!");
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.