Reputation: 145
I am trying to work on a sample example to map CustomerViewItem(Source) and Customer(Destination).
Here is the Source Entities that I am trying to map
public class CustomerViewItem
{
public CompanyViewItem companyViewItem { get; set; }
public string CompanyName { get; set; }
public int CompanyEmployees { get; set; }
public string CompanyType { get; set; }
public string FullName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public int NumberOfOrders { get; set; }
public bool VIP { get; set; }
}
public class Customer
{
public Company company { get; set; }
public string CompanyName { get; set; }
public int CompanyEmployees { get; set; }
public string CompanyType { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public int NumberOfOrders { get; set; }
public bool VIP { get; set; }
}
public class Address
{
public string TempAddress { get; set; }
public string PermAddress { get; set; }
}
public class Company
{
public string Name { get; set; }
public int Employees { get; set; }
public string Type { get; set; }
public Address address { get; set; }
}
public class CompanyViewItem
{
public string Name { get; set; }
public int Employees { get; set; }
public string Type { get; set; }
public Address address { get; set; }
}
Now for the CustomerViewItem Entity, I have added some sample values. Since the CompanyViewItem in the CustomerViewItem is a class which in turn had a class, I have added the values in this way
companyViewItem = new CompanyViewItem() { address = new Address { PermAddress = "pAdd", TempAddress = "tAdd" }, Employees = 15, Name = "name", Type = "abc" }
Now here is my AutoMapper code:
Mapper.CreateMap<CustomerViewItem, Customer>();
CustomerViewItem customerViewItem = GetCustomerViewItemFromDB();
Customer customer = Mapper.Map<CustomerViewItem,Customer>customerViewItem);
Everything is running fine but, only company in returning null. I have tried in vice versa too, the same is returning null. Could some one help me out with this?
Upvotes: 3
Views: 15907
Reputation: 2947
If you were getting mapper.map()
returning null in your unit tests, make sure you do not mock the automapper dependency to whatever service you are testing, but instead use the real thing.
Upvotes: 8
Reputation: 3611
You are missing mapping configuration between CompanyViewItem
and Company
:
Mapper.CreateMap<CompanyViewItem, Company>();
Your mapping code should be something like:
// Setup
Mapper.CreateMap<CustomerViewItem, Customer>()
.ForMember(dest => dest.company, opt => opt.MapFrom(src => src.companyViewItem));
Mapper.CreateMap<CompanyViewItem, Company>();
CustomerViewItem customerViewItem = GetCustomerViewItemFromDB();
// Mapping
Customer customer = Mapper.Map<CustomerViewItem,Customer>(customerViewItem);
Upvotes: 6