Reputation: 7555
I am new to Automapper. With below links, I am trying to understand it in action.
I am using its Automapper v 5.2.0
Here is my stuff. https://codepaste.net/xph2oa
class Program
{
static void Main(string[] args)
{
//PLEASE IGNORE NAMING CONVENTIONS FOR NOW.Sorry!!
//on Startup
AppMapper mapperObj = new AppMapper();
mapperObj.Mapping();
DAL obj = new DAL();
var customer = obj.AddCustomers();
}
}
class Customer
{
public int CustomerId { get; set; }
public string CustName { get; set; }
}
class CustomerTO
{
public int CustId { get; set; }
public object CustData { get; set; }
}
class AppMapper
{
public void Mapping()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Customer, CustomerTO>();
});
IMapper mapper = config.CreateMapper();
}
}
class DAL
{
public IEnumerable<CustomerTO> AddCustomers()
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer() { CustName = "Ram", CustomerId = 1 });
customers.Add(new Customer() { CustName = "Shyam", CustomerId = 2 });
customers.Add(new Customer() { CustName = "Mohan", CustomerId = 3 });
customers.Add(new Customer() { CustName = "Steve", CustomerId = 4 });
customers.Add(new Customer() { CustName = "John", CustomerId = 5 });
return customers; //throws error
}
}
Error -Cannot implicitly convert type System.Collections.Generic.List' to ' System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)
How do I map List<Customer>
to List<CustomerTO>
?
Please note, in Customer
I have property of type string
with name Custname
while CustomerTO
I have the property with name CustData
of type object
.
So how do I map this different name property?
Thanks.
Upvotes: 0
Views: 896
Reputation: 1187
Using the same names for properties in the types to be mapped is the simplest way to us AutoMapper. That way the config you have now will work.
However, in the case where you don't do that you need to specify how the properties are to be mapped, as follows
cfg.CreateMap<Customer, CustomerTO>()
.ForMember(dto => dto.CustData, opt => opt.MapFrom(entity => entity.CustName))
.ForMember(dto => dto.CustId, opt => opt.MapFrom(entity, entity.CustomerId));
I'm assuming that you want to straight map CustName
to CustData
above, and this will work fine.
Upvotes: 1