首页 > 解决方案 > EFCore 在 automapper 上的绑定器设置 int?=> 整数?将 null 值设为 0 而不是 null

问题描述

我想映射一个int?到一个整数?使用 Automapper(使用 EFCore)的成员。但是,当调用映射器时,如果该字段的值为 null,则映射的值为 0(而不是 null)。我怀疑这是由于https://www.fuget.org/packages/AutoMapper/6.2.2/lib/netstandard1.1/AutoMapper.dll/AutoMapper.QueryableExtensions/NullableSourceExpressionBinder?code=true EFCore 添加到映射器的活页夹. 我发现没有办法(还)强制一个 null int?被映射到......一个null int?

这是 DTO、实体和映射器配置文件的简短版本:

DTO:

public class MyDto
{
    public int Id
    public int? AnotherClassId{ get; set; }
}

实体映射:

public class MyEntity
{
    public int Id
    public int? AnotherClassId{ get; set; }
}

MapperProfile(短版):

public class MyBackEndAutoMapperProfile : Profile
{
    public MyBackEndAutoMapperProfile()
    {
        CreateMap<MyEntity, MyDto>()
            .ReverseMap();
    }
}

调用示例:

var myEntity = _mapper.Map<MyEntity>(myDto);

myDto 是 MyDto 的类型,AnotherClassId 的值为 null,myEntity 的 AnotherClassId 值为 0,而我希望它为 null。

需要注意的一点是,AnotherClass 的 Id 成员不为空,但在模型构建器中,配置允许从 MyENTity 到 AnotherClass 的 FK 为空(可为空的列)。

映射器是这样配置的:

services.AddAutoMapper((provider, mapper) =>
        {
            mapper.AddCollectionMappers();
            mapper.UseEntityFrameworkCoreModel<MyDbContext>(provider);
        }, Assembly.GetAssembly(typeof(MyBackEndAutoMapperProfile )));

标签: c#entity-framework-coreautomapper

解决方案


推荐阅读