AutoMapper C#實體映射
阿新 • • 發佈:2018-12-12
斷點 實體映射 mobile model類 http close bsp 新版 pla
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 被映射實體
1View Codepublic 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; } } }
AutoMapper C#實體映射