c# - Automapper 禁用 IgnoreMap 属性一次
问题描述
我的目标实体中有一个具有 IgnoreMap 属性的属性。
我只想禁用一次。我使用 Automapper 列表来列出映射。
public class TestDto {
public string Name { get; set; }
public DateTime UpdateDate { get; set; }
}
public class Test {
public string Name { get; set; }
//Normally, I want to ignore this entities all mapping except one method.
[IgnoreMap]
public DateTime UpdateDate { get; set; }
}
class Program {
public void MapMethod(List<TestDto> sourceList)
{
var content = new MapperConfigurationExpression();
content.CreateMap<TestDto,Test>();
var config = new MapperConfiguration(content);
var mapper = config.CreateMapper();
//I do not want to ignore UpdateDate entity in here.
var destinationList = mapper.Map<List<Test>>(sourceList);
}
}
解决方案
你可以试试这个:
_mapper.Map<DestType>(result, options => options.AfterMap((s, d) => ((DestType) d).Code = null));
完整示例
void Main()
{
IConfigurationProvider conf = new MapperConfiguration(exp => exp.CreateMap<Src, Dest>());
IMapper mapper = new Mapper(conf);
var src = new Src(){
Id =1,
Name= "John Doe"
};
var result = mapper.Map<Dest>(src, options => options.AfterMap((s, d) => ((Dest) d).Name = null));
result.Dump();
var result2 = mapper.Map<List<Dest>>(srcList, options => options.AfterMap((s, d) => ((List<Dest>) d).ForEach(i => i.Name = null)));
result2.Dump();
}
public class Src
{
public int Id {get; set;}
public string Name {get; set;}
}
public class Dest
{
public int Id {get; set;}
public string Name {get; set;}
}
或者
void ConfigureMap(IMappingOperationOptions<Src, Dest> opt)
{
opt.ConfigureMap()
.ForMember(dest => dest.Name, m => m.Ignore());
};
var result3 = mapper.Map<List<Dest>>(srcList, ConfigureMap());
result3.Dump();
推荐阅读
- go - 迁移具有多个主机 ip 的 cassandra 库实现
- php - PDO 方法 rowCount() 是否可以为插入过程返回 int 0 而不会像在更新过程中那样被捕获?
- reactjs - 意外的令牌:Webpack、reactjs 和 babel
- sql - SQL 从 XML 中提取值
- html - 长文本导致 div 高度问题
- android - Android ndk r15c 编译 node.js 错误:“to_string”不是“std”的成员
- java - MainActivity 无法转换接口
- sql-server - 使用 DATEDIFF 获取最近六个月的结果
- javascript - 有没有办法在窗口加载事件中停止加载某些资源以提高站点性能?
- c# - Asp.net Core 中的 Ajax 助手标签