AutoMapper是对象到对象的映射工具。在完成映射规则之后,AutoMapper可以将源对象转换为目标对象。
要映射实体
1
public
class
SourceModel
2
{
3
public
int ID { get; set; }
4publicstring Name { get; set; }
5publicstring Address { get; set; }
6publicstring Mobile { get; set; }
7 }
被映射实体
1
public
class
YingSheModel
2
{
3
public
string Name { get; set; }
4publicstring Address { get; set; }
5 }
需要将SourceModel类的对象映射到YingSheModel类的对象上面。需要对AutoMapper进行如下配置:
//注:Mapper.CreateMap由于nuget的最新版本用法改变了无法使用
Mapper.Initialize(cret => cret.CreateMap<SourceModel, YingSheModel>())
效果展示:
全部代码:
using
AutoMapper;
using
System;
namespace
Mapping
{
class
Program
{
static
void Main(string[] args)
{
Mapper.Initialize(cret => cret.CreateMap<SourceModel, YingSheModel>());//配置
SourceModel sources = new SourceModel() { ID = 1, Name = "特朗普", Address = "北京市洪山区", Mobile = "18712457845" }; //给实体赋初始数据
YingSheModel dest = Mapper.Map<YingSheModel>(sources);//看这里的断点
var model = new
{
name = dest.Name,
address = dest.Address
};
Console.WriteLine(model);
Console.ReadKey();
}
}
public
class
SourceModel
{
public
int ID { get; set; }
publicstring Name { get; set; }
publicstring Address { get; set; }
publicstring Mobile { get; set; }
}
publicclass YingSheModel
{
publicstring Name { get; set; }
publicstring Address { get; set; }
}
}
原文:https://www.cnblogs.com/xiasy-bk/p/10109823.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!