简单的C#实体映射 AutoMapper
程序员文章站
2022-03-23 19:21:19
AutoMapper是对象到对象的映射工具。在完成映射规则之后,AutoMapper可以将源对象转换为目标对象。 1 public class SourceModel 2 { 3 public int ID { get; set; } 4 public string Name { get; set; ......
automapper是对象到对象的映射工具。在完成映射规则之后,automapper可以将源对象转换为目标对象。
要映射实体
1 public class sourcemodel 2 { 3 public int id { get; set; } 4 public string name { get; set; } 5 public string address { get; set; } 6 public string mobile { get; set; } 7 }
被映射实体
1 public class yingshemodel 2 { 3 public string name { get; set; } 4 public string 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; } public string name { get; set; } public string address { get; set; } public string mobile { get; set; } } public class yingshemodel { public string name { get; set; } public string address { get; set; } } }
上一篇: HTML常用标签及属性
下一篇: 微软称霸VR界的野心,能这么轻易实现吗?