C# Automapper没有';它不能正常工作
我使用的是C# Automapper没有';它不能正常工作,c#,automapper,automapper-4,C#,Automapper,Automapper 4,我使用的是AutoMapper 4.2.1.0,我已将我的地图定义如下 var config = new MapperConfiguration(cfg => { cfg.CreateMap<Order, OrderDTO>(); cfg.CreateMap<Order_Detail, Order_DetailDTO>(); }); MapperConfig = config; 但是
AutoMapper 4.2.1.0
,我已将我的地图定义如下
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Order, OrderDTO>();
cfg.CreateMap<Order_Detail, Order_DetailDTO>();
});
MapperConfig = config;
但是当TEntity
是Order
并且TDto
是OrderDto
时,我得到一个异常,它说:
缺少从Order到OrderDTO的映射。创建使用
Mapper.CreateMap
我做错了什么?您需要使用MapperConfiguration对象创建映射器
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Order, OrderDTO>();
cfg.CreateMap<Order_Detail, Order_DetailDTO>();
});
// Make sure mappings are properly configured (you can try-catch this).
config.AssertConfigurationIsValid();
// Create a mapper to use for auto mapping.
var mapper = config.CreateMapper();
var orderObject = new Order { /* stuff */ };
var orderDto = mapper.Map<OrderDTO>(orderObject);
var config=new-MapperConfiguration(cfg=>
{
CreateMap();
CreateMap();
});
//确保映射已正确配置(您可以尝试捕获此映射)。
config.assertconfigurationsvalid();
//创建用于自动映射的映射器。
var mapper=config.CreateMapper();
var orderObject=新订单{/*stuff*/};
var orderDto=mapper.Map(orderObject);
好的。我明白了:
而不是:
return ((IQueryable<TEntity>) property.GetValue(_db, null)).ProjectTo<TDto>(builder);
return((IQueryable)property.GetValue(_db,null)).ProjectTo(builder);
我应该写:
return ((IQueryable<TEntity>) property.GetValue(_db, null)).ProjectTo<TDto>(MapperConfig);
return((IQueryable)property.GetValue(_db,null)).ProjectTo(MapperConfig);
将配置对象本身传递到ProjectTo。我想使用
ProjectTo
,因此我必须像本文中提到的那样使用ExpressionBuilder:
return ((IQueryable<TEntity>) property.GetValue(_db, null)).ProjectTo<TDto>(MapperConfig);