[C#] 使用 AutoMapper 快速轉換有相同資料的 Model

因為工作因素發生了需要將兩個具有相同資料的Model進行轉換,但是如果手動轉換的話太累了,工程師就是懶嘛~
於是乎就拜了Google大神找到了一個名叫AutoMapper套件。

 

  1. 從NuGet下載AutoMapper
    01
  2. 新增兩組相同的Model
    class Model_1
    {
    	public string Name { get; set; }
    
    	public int Year { get; set; }
    
    	public DateTime Date { get; set; }
    }
    
    class Model_2
    {
    	public string Name { get; set; }
    
    	public int Year { get; set; }
    
    	public DateTime Date { get; set; }
    }
    
  3. 轉換用的方法
    static TModel_2 ConvertModelToModel<TModel_1, TModel_2>(TModel_1 list)
    {
    	Mapper.Initialize(cfg =>
    	{
    		cfg.CreateMissingTypeMaps = true;
    		cfg.CreateMap<TModel_1, TModel_2>().ReverseMap();
    	});
    	Mapper.Configuration.AssertConfigurationIsValid();
    
    	var converted = Mapper.Map<TModel_2>(list);
    	return converted;
    }
  4. 轉換
    static void Main(string[] args)
    {
    	Model_1 model1 = new Model_1();
    	Model_2 model2 = new Model_2();
    
    
    	model1.Name = "王小明";
    	model1.Year = 2016;
    	model1.Date = DateTime.UtcNow.AddHours(8);
    
    
    	Console.WriteLine("=== 轉換前 ===");
    	Console.WriteLine("model1=name:{0}, year:{1}, date:{2}, type:{3}", model1.Name, model1.Year, model1.Date, model1.GetType());
    	Console.WriteLine("model2=name:{0}, year:{1}, date:{2}, type:{3}", model2.Name, model2.Year, model2.Date, model2.GetType());
    
    	model2 = ConvertModelToModel<Model_1, Model_2>(model1);
    
    	Console.WriteLine("=== 轉換後 ===");
    	Console.WriteLine("model1=name:{0}, year:{1}, date:{2}, type:{3}", model1.Name, model1.Year, model1.Date, model1.GetType());
    	Console.WriteLine("model2=name:{0}, year:{1}, date:{2}, type:{3}", model2.Name, model2.Year, model2.Date, model2.GetType());
    
    	Console.ReadLine();
    }
  5. 結果
    02

 

原始碼:https://github.com/shuangrain/ConsoleApplication_AutoMapper



這裡的資訊對您有用嗎?歡迎斗內給我