c# - 如果对象成员没有值,如何为对象分配 null - automapper c#
问题描述
我在 C# 中使用自动映射器。
class A
{
public int Value { get; set; }
public string Code { get; set; }
public B? Details { get; set; }
}
class B
{
public int Id { get; set;}
public string Name { get; set; }
}
class C
{
public int Value { get; set; }
public string Code { get; set; }
public int? DetailId { get; set; }
public string? DetailName { get; set; }
}
在自动映射器中我使用如下:
CreateMap<C, A>()
.ForPath(o => o.Details.Id, b => b.MapFrom(z => z.DetailId))
.ForPath(o => o.Details.Name, b => b.MapFrom(z => z.DetailName))
.ReverseMap();
当我使用上述映射时,我得到的输出如下
"details ": {
"id": 0,
"name": ""
}
Details
如果它的成员没有值,我需要将值作为 null 而不是对象类型。即)DetailId
并且DetailName
没有价值。如何得到这个?
"details" : null
解决方案
您可以使用条件映射
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<C, B>()
.ForMember(o => o.Id, b => b.MapFrom(z => z.DetailId))
.ForMember(o => o.Name, b => b.MapFrom(z => z.DetailName));
cfg.CreateMap<C, A>()
.ForMember(o => o.Details, b => b.MapFrom((c, a, obj, context) => !string.IsNullOrEmpty(c.DetailName) ? context.Mapper.Map<B>(c) : null))
.ReverseMap();
});
推荐阅读
- javascript - React/Redux - 休息操作员没有按预期工作
- spring - 我们可以将直接引导模板添加到我们的 spring mvc 应用程序吗?
- javascript - 参数未传递给 window.onerror 函数
- excel - vba excel宏使用adb
- python - BeautifulSoup 如果找不到返回 0 而不是 None
- javascript - 如何附加从特定列开始的值
- drools - 如何修复:Eclipse Builder 错误 - Drools
- php - 电子邮件点击时laravel中的上一个网址
- php - Codeigniter,Benchmark,大括号'{pseudo-variables}'中的伪变量语法含义?
- reactjs - React Native Firebase 状态未定义