- 创建和使用Map
Mapper.CreateMap<SourceType, DestinationType>()
.ForMember(dest=> dest.Property, opt => opt.MapFrom(src => src.OtherProperty))
.ForMember(dest => dest.IgnoreProperty, opt => opt.Ignore());
然后就可以使用这个Map了:
DestinationType dest = Mapper.Map<SourceType, DestinationType>(source);
- Mapper.AssertConfigurationIsValid(); 用于检查映射是否完整,Destinate model的没被忽略的字段必须全都被映射到位,否则就会被这个方法给报出错误来!
- 如果想忽略所有的不存在对应的属性,可以写一个扩展方法:
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination> (this IMappingExpression<TSource, TDestination> expression) { const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; var sourceType = typeof (TSource); var destinationProperties = typeof (TDestination).GetProperties(flags); foreach (var property in destinationProperties) { if (sourceType.GetProperty(property.Name, flags) == null) { expression.ForMember(property.Name, opt => opt.Ignore()); } } return expression; }
使用方式:
Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting() .ForMember(prop => x.Property, opt => opt.MapFrom(src => src.OtherProperty));
改正:InnoreAllNonExisting这个扩展方法最好不要放在ForMember之后,因为ForMember主要用于手动映射一些名称不一样的属性,映射好了后你又来个IgnoreAll, 得~,手动映射全部失效,白搭了,所以最好是放在在CreateMap后。
-
如果你想在使用Map的时候不创建一个新的对象,该怎么做呢? 很简单:
Mapper.Map<Source, Destination>(source, destination);
-
AutoMapper也是可以轻松转换List的:
Mapper.CreateMap<SourceType, DestinationType>();
List<Destination> destList = Mapper.Map<List<Source>, List<Destination>(sourceList);
-
既然知道怎么创建映射了,也知道怎么使用映射了,我们可以再写一些扩展方法,把映射转换放在扩展方法里,这样来调用的代码更为简洁,都看不到Mapper的踪影,举个例子:
public
static
class
MapperExtensions
{
// Company
public
static
Company ToEntity(
this
CompanyViewModel model)
{
return
Mapper.Map<CompanyViewModel, Company>(model);
}
public
static
Company ToEntity(
this
CompanyViewModel model, Company entity)
{
return
Mapper.Map(model, entity);
}
public
static
CompanyViewModel ToModel(
this
Company entity)
{
return
Mapper.Map<Company, CompanyViewModel>(entity);
}
public
static
List<CompanyViewModel> ToModelList(
this
List<Company> entities)
{
return
Mapper.Map<List<Company>, List<CompanyViewModel>>(entities);
}
}
调用方式:
var
model = entity.ToModel();
var
entity = model.ToEntity();
var
entity = model.ToEntity(entity);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构