Beatles1692
Beatles1692

Reputation: 5320

Automapper doesn't work as it should

I am using AutoMapper 4.2.1.0 and I have defined my maps as follow.

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

Then I use MapperConfig in my code to do this :

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

but when TEntity is Order and TDto is OrderDto i am getting an exception that says :

Missing map from Order to OrderDTO. Create using Mapper.CreateMap

What did I do wrong ?

Upvotes: 1

Views: 951

Answers (2)

Beatles1692
Beatles1692

Reputation: 5320

OK. I have got it: Instead of :

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

I should write :

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

Passing the config object itself into ProjectTo.

Upvotes: 2

Niclas Lindstedt
Niclas Lindstedt

Reputation: 104

You need to create a mapper using the MapperConfiguration object.

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);

Upvotes: 1

Related Questions