c# - 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 )));
解决方案
推荐阅读
- slick - 包含在 for 理解中的 DBIOAction 是否总是按顺序运行?
- python - BeautifulSoup 返回 None 即使 (div = "pendingcasescnts ng-scope") 元素存在
- python - 使用 Python 向 Google Cloud Storage 写入流式传输
- nativescript - 调用 builder.load 然后复制组件
- ubuntu - 在 ubuntu 18.04 上安装 v8js
- python - 将来自 SurveyMonkey 调查的所有调查回复导入 csv
- python - 获取重复时间的日期时间对象列表
- java - 使递归函数迭代
- azure - 嵌套的 ARM 模板和依赖
- elasticsearch - Ngram 不像配置的那样工作