Mapping DTOs to Entities using AutoMapper and EntityFramework

In this blog you will learn how to mapping DTOs to Entities using AutoMapper and EntityFramework. Mapping DTOs to Entities using AutoMapper and EntityFramework.

Here we have an Entity class Country and an CountryDTO:

  1. public class Country  
  2. {  
  3.       public int CountryID { getset; }  
  4.       public string ContryName { getset; }  
  5.       public string CountryCode { getset; }    
  6. }  
  7.   
  8. CountryDto  
  9. public class CountryDTO  
  10. {  
  11.       public int CountryID { getset; }  
  12.       public string ContryName { getset; }  
  13.       public string CountryCode { getset; }    
  14. }  
  15. Create Object of CountryDTO  
  16. CountryDTO collection=new CountryDTO();  
  17. collection.CountryID =1;  
  18. collection.ContryName ="India";  
  19. collection.CountryCode ="in";  
  20.   
  21. Country model = Convertor.Convert<Country, CountryDTO>(collection);  
  22. dbcontext.Countries.Add(model);  
  23. dbcontext.SaveChanges();   
This will work fine for a new Country, the above code will map CountryDTO to Country Entity Object and add new entities to the dbcontext and save the changes.
  1. using System.Reflection;  
  2. public static TOut Convert<TOut, TIn>(TIn fromRecord) where TOut : new()  
  3. {  
  4.       var toRecord = new TOut();  
  5.       PropertyInfo[] fromFields = null;  
  6.       PropertyInfo[] toFields = null;  
  7.   
  8.       fromFields = typeof(TIn).GetProperties();  
  9.       toFields = typeof(TOut).GetProperties();  
  10.   
  11.       foreach (var fromField in fromFields)  
  12.       {  
  13.             foreach (var toField in toFields)  
  14.             {  
  15.                   if (fromField.Name == toField.Name)  
  16.                   {  
  17.                         toField.SetValue(toRecord, fromField.GetValue(fromRecord, null), null);  
  18.                         break;  
  19.                   }  
  20.             }  
  21.   
  22.       }  
  23. return toRecord;  
  24. }  
  25.   
  26. public static List<TOut> Convert<TOut, TIn>(List<TIn> fromRecordList) where TOut : new()  
  27. {  
  28.       return fromRecordList.Count == 0 ? null : fromRecordList.Select(Convert<TOut, TIn>).ToList();  
  29. }  
Reference

ASP.Net and Sql Server Articles