经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
简单的C#实体映射 AutoMapper
来源:cnblogs  作者:playsun94  时间:2018/12/13 9:37:21  对本文有异议

AutoMapper是对象到对象的映射工具。在完成映射规则之后,AutoMapper可以将源对象转换为目标对象。

要映射实体
  1. 1 public class SourceModel
  2. 2 {
  3. 3 public int ID { get; set; }
  4. 4 public string Name { get; set; }
  5. 5 public string Address { get; set; }
  6. 6 public string Mobile { get; set; }
  7. 7 }
View Code
被映射实体
  1. 1 public class YingSheModel
  2. 2 {
  3. 3 public string Name { get; set; }
  4. 4 public string Address { get; set; }
  5. 5 }
View Code

需要将SourceModel类的对象映射到YingSheModel类的对象上面。需要对AutoMapper进行如下配置:

  1. //注:Mapper.CreateMap由于nuget的最新版本用法改变了无法使用
  1. Mapper.Initialize(cret => cret.CreateMap<SourceModel, YingSheModel>())

效果展示:

 

全部代码:

  1. using AutoMapper;
  2. using System;
  3. namespace Mapping
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. Mapper.Initialize(cret => cret.CreateMap<SourceModel, YingSheModel>());//配置
  10. SourceModel sources = new SourceModel() { ID = 1, Name = "特朗普", Address = "北京市洪山区", Mobile = "18712457845" }; //给实体赋初始数据
  11. YingSheModel dest = Mapper.Map<YingSheModel>(sources);//看这里的断点
    var model = new
    {
                  name = dest.Name,
                  address = dest.Address
                 };
                 Console.WriteLine(model);
    Console.ReadKey();

    }
  1. }
  2. public class SourceModel
  3. {
  4. public int ID { get; set; }
  5. public string Name { get; set; }
  6. public string Address { get; set; }
  7. public string Mobile { get; set; }
  8. }
  9. public class YingSheModel
  10. {
  11. public string Name { get; set; }
  12. public string Address { get; set; }
  13. }
  14. }

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号