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:
- public class Country
- {
- public int CountryID { get; set; }
- public string ContryName { get; set; }
- public string CountryCode { get; set; }
- }
-
- CountryDto
- public class CountryDTO
- {
- public int CountryID { get; set; }
- public string ContryName { get; set; }
- public string CountryCode { get; set; }
- }
- Create Object of CountryDTO
- CountryDTO collection=new CountryDTO();
- collection.CountryID =1;
- collection.ContryName ="India";
- collection.CountryCode ="in";
-
- Country model = Convertor.Convert<Country, CountryDTO>(collection);
- dbcontext.Countries.Add(model);
- 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.
- using System.Reflection;
- public static TOut Convert<TOut, TIn>(TIn fromRecord) where TOut : new()
- {
- var toRecord = new TOut();
- PropertyInfo[] fromFields = null;
- PropertyInfo[] toFields = null;
-
- fromFields = typeof(TIn).GetProperties();
- toFields = typeof(TOut).GetProperties();
-
- foreach (var fromField in fromFields)
- {
- foreach (var toField in toFields)
- {
- if (fromField.Name == toField.Name)
- {
- toField.SetValue(toRecord, fromField.GetValue(fromRecord, null), null);
- break;
- }
- }
-
- }
- return toRecord;
- }
-
- public static List<TOut> Convert<TOut, TIn>(List<TIn> fromRecordList) where TOut : new()
- {
- return fromRecordList.Count == 0 ? null : fromRecordList.Select(Convert<TOut, TIn>).ToList();
- }
Reference
ASP.Net and Sql Server Articles