AutoMapper is used to map data from object to objects.
In a real project the entity layers always deal with the communication from services or Data Layer.To show the data in the application we need separate class as ViewModel or Model class . UI Layers may or may not be synced with the entities. So to Map entities to model or viewModel we need AutoMapper.
Let us see how to do that,
First we need to get the AutoMapper from the Nuget package as shown below.
Let us say we have a class at entity layer as below,
We need to create a class i.e Employee.cs at entity layer as below,
- using System;
-
- namespace DemoEntities
- {
-
-
-
- public class Employee
- {
- public int EmployeeId { get; set; }
- public string EmployeeFName { get; set; }
- public string EmployeeLName { get; set; }
- public string Address { get; set; }
- public string City { get; set; }
- public string State { get; set; }
- public string Zip { get; set; }
- public DateTime? DateOfJoining { get; set; }
-
- }
- }
We have another class called User class at UI Layer.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace DemoAutomapper.Models
- {
-
-
-
-
-
- public class User
- {
- public int Userid { get; set; }
- public string UserFName { get; set; }
- public string UserLName { get; set; }
- public string Address { get; set; }
- public string City { get; set; }
- public string State { get; set; }
- public string Zip { get; set; }
- public DateTime? DateOfJoining { get; set; }
-
- }
- }
We want to map Employee class to a User class, by using Automapper we can map as below,
- Employee objEmployee = new Employee
- {
- EmployeeId = 1001,
- EmployeeFName = "Pradeep",
- EmployeeLName = "Sahoo",
- Address = "KRPURAM",
- City = "BANGALORE",
- State = "KA",
- Zip = "560049",
- DateOfJoining = DateTime.Now,
- };
-
-
- Mapper.CreateMap<Employee, User>();
-
-
- If properties are different we need to map fields of employee to that of user as below.
-
- AutoMapper.Mapper.CreateMap<Employee, User>()
- .ForMember(o => o.Userid, b => b.MapFrom(z => z.EmployeeId))
- .ForMember(o => o.UserFName, b => b.MapFrom(z => z.EmployeeFName))
- .ForMember(o => o.UserLName, b => b.MapFrom(z => z.EmployeeLName));
-
- User objuser = Mapper.Map<Employee, User>(objEmployee);
Let us see the output,
We saw how to map Entities to Model class using AutoMapper. Thanks for reading.