当前位置: 移动技术网 > IT编程>开发语言>.net > 简单的C#实体映射 AutoMapper

简单的C#实体映射 AutoMapper

2018年12月13日  | 移动技术网IT编程  | 我要评论

王华滔,拉萨阳光泌尿生殖医院,开学第一课2013

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     }
view code
被映射实体
1  public class yingshemodel
2     {
3         public string name { get; set; }
4         public string address { get; set; }
5     }
view code

需要将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; }
    }
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网