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();
- 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();
- }
ASP.Net and Sql Server Articles

Ali GhaffariPosted Nov 24, 2021, 11:39 AM
If we add new field in our Entity and not updated DTO then will be showing null after conversion.
Ali GhaffariPosted Nov 24, 2021, 11:38 AM
This one is good article.