簡單的C#實體映射 AutoMapper


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的最新版本用法改變了無法使用
//AutoMapper-8.1.0版本
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; } } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM