C# 如何使用Automapper 5?
我是汽车制造商的新手。通过下面的链接,我正在努力理解它的实际作用C# 如何使用Automapper 5?,c#,asp.net,automapper,automapper-5,C#,Asp.net,Automapper,Automapper 5,我是汽车制造商的新手。通过下面的链接,我正在努力理解它的实际作用 我正在使用它的AutomapperV5.2.0 这是我的东西。 类程序 { 静态void Main(字符串[]参数) { //请暂时忽略命名约定。对不起!! //启动时 AppMapper mapperbj=新的AppMapper(); mapperbj.Mapping(); DAL obj=新的DAL(); var customer=obj.AddCustomers(); } } 类客户 { public int Cu
类程序
{
静态void Main(字符串[]参数)
{
//请暂时忽略命名约定。对不起!!
//启动时
AppMapper mapperbj=新的AppMapper();
mapperbj.Mapping();
DAL obj=新的DAL();
var customer=obj.AddCustomers();
}
}
类客户
{
public int CustomerId{get;set;}
公共字符串CustName{get;set;}
}
类CustomerTO
{
public int CustId{get;set;}
公共对象CustData{get;set;}
}
类映射器
{
公共void映射()
{
var config=new-MapperConfiguration(cfg=>
{
CreateMap();
});
IMapper mapper=config.CreateMapper();
}
}
DAL类
{
公共IEnumerable AddCustomers()
{
列出客户=新列表();
添加(新客户(){CustName=“Ram”,CustomerId=1});
添加(新客户(){CustName=“Shyam”,CustomerId=2});
添加(新客户(){CustName=“Mohan”,CustomerId=3});
添加(新客户(){CustName=“Steve”,CustomerId=4});
添加(新客户(){CustName=“John”,CustomerId=5});
返回客户;//抛出错误
}
}
错误-无法将System.Collections.Generic.List类型隐式转换为
'System.Collections.Generic.IEnumerable'。存在显式转换(是否缺少强制转换?)
如何将列表
映射到列表
?请注意,在
Customer
中,我拥有类型为string
且名称为Custname
的属性,而CustomerTO
中,我拥有类型为object
且名称为CustData
的属性。
那么如何映射这个不同的名称属性呢
谢谢。对要映射的类型中的属性使用相同的名称是使用AutoMapper的最简单方法。这样,您现在的配置就可以工作了 但是,如果不这样做,则需要指定映射属性的方式,如下所示
cfg.CreateMap<Customer, CustomerTO>()
.ForMember(dto => dto.CustData, opt => opt.MapFrom(entity => entity.CustName))
.ForMember(dto => dto.CustId, opt => opt.MapFrom(entity, entity.CustomerId));
cfg.CreateMap()
.ForMember(dto=>dto.CustData,opt=>opt.MapFrom(entity=>entity.CustName))
.ForMember(dto=>dto.CustId,opt=>opt.MapFrom(entity,entity.CustomerId));
我假设您希望直接将上面的
CustName
映射到CustData
,这将很好地工作。检查我认为这将对您有所帮助。但是我不知道你是否能从字符串映射到对象你看过wiki了吗?它有最新的文档,而不是我的博客,因为我的博客可能已经过时了(例如,静态API仍然存在,将来也会存在)。@JimmyBogard,谢谢你的博客。你的博客+其他链接足够我开始了。我还没有查看wiki。假设我在Customer&CustomerTO中有10多个属性。9个属性名称相同,但1个属性名称和类型不同。在这种情况下,我需要编写。FormMember 10次??不,您只需要指定不同名称的成员。请检查更新后的帖子,我得到了构建错误,在DAL方法中,您在AddCustomers()
方法的任何点上都没有实际从Customer
映射到CustomerTO
。您需要调用.Map(客户)在你的AppMapper
类的一个实例上执行code>操作。在Main()中,我执行了,所以我需要再次关联这个映射胶水??
cfg.CreateMap<Customer, CustomerTO>()
.ForMember(dto => dto.CustData, opt => opt.MapFrom(entity => entity.CustName))
.ForMember(dto => dto.CustId, opt => opt.MapFrom(entity, entity.CustomerId));