如何使用Automapper 5? [英] How to use Automapper 5?
问题描述
我是Automapper的新手.通过下面的链接,我试图了解它的作用.
I am new to Automapper. With below links, I am trying to understand it in action.
- http://automapper.org/
- https://lostechies. com/jimmybogard/2016/01/21/removing-the-static-api-from-automapper/
- http://automapper.org/
- https://lostechies.com/jimmybogard/2016/01/21/removing-the-static-api-from-automapper/
我正在使用其Automapper v 5.2.0
I am using its Automapper v 5.2.0
这是我的东西. 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
}
}
错误-无法将类型System.Collections.Generic.List隐式转换为 'System.Collections.Generic.IEnumerable'.存在显式转换(您是否缺少演员表?)
Error -Cannot implicitly convert type System.Collections.Generic.List' to ' System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)
如何将List<Customer>
映射到List<CustomerTO>
?
How do I map List<Customer>
to List<CustomerTO>
?
请注意,在Customer
中,我具有名称为Custname
的string
类型的属性,而在CustomerTO
中,我具有类型为object
的名称CustData
的属性.
那么如何映射这个不同的name属性?
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?
谢谢.
推荐答案
对于要映射的类型中的属性,使用相同的名称是使用AutoMapper的最简单方法.这样,您现在的配置便可以使用.
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));
我假设您想将CustName
映射到上面的CustData
,这样就可以正常工作.
I'm assuming that you want to straight map CustName
to CustData
above, and this will work fine.
这篇关于如何使用Automapper 5?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!