簡體   English   中英

Automapper無法正常工作

[英]Automapper doesn't work as it should

我正在使用AutoMapper 4.2.1.0並且已經按照以下方式定義了地圖。

 var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Order, OrderDTO>();
            cfg.CreateMap<Order_Detail, Order_DetailDTO>();
        });
MapperConfig = config;

然后我在代碼中使用MapperConfig來做到這一點:

var builder = MapperConfig.ExpressionBuilder;
return ((IQueryable<TEntity>) property.GetValue(_db, null)).ProjectTo<TDto>(builder);

但是當TEntityOrderTDtoOrderDto時,我得到了一個異常:

從Order到OrderDTO的地圖丟失。 使用Mapper.CreateMap創建

我做錯了什么 ?

好。 我知道了:而不是:

return ((IQueryable<TEntity>) property.GetValue(_db, null)).ProjectTo<TDto>(builder);

我應該寫:

return ((IQueryable<TEntity>) property.GetValue(_db, null)).ProjectTo<TDto>(MapperConfig);

將配置對象本身傳遞到ProjectTo。

您需要使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM