MANISH KUMAR CHOUDHARY
MANISH KUMAR CHOUDHARY

Reputation: 3482

AutoMapper projection error

I have get method in web api:

public async Task<IHttpActionResult> Get()
{
   var categories = await _context.Categories.Include(x => x.SubCategories)
                                  .Where(c => c.IsActive)
                                  .ToListAsync();
   var outPut = AutoMapper.Mapper.Map<List<CategoryDto>>(categories);
   return Ok(outPut);
}

This method is working as expected. But I don't want to retrieve all the records from database and then map to DTO and return the result.I want to use AutoMapper.QueryableExtensions and select only the required field.

var categories = await _context.Categories.Include(x => x.SubCategories)
                                          .Where(c => c.IsActive)
                                          .ProjectTo<List<CategoryDto>>()
                                          .ToListAsync();

In mapping configuration I defined mapping like:

public static void Config()
{
    AutoMapper.Mapper.Initialize(config =>
    {
        config.CreateMap<SubCategory, SubCategoryDto>();
        config.CreateMap<Category, CategoryDto>().ForMember(
                    des=>des.SubCategoriesCount,
                    opt=>opt.MapFrom(src=>src.SubCategories.Count));
    });

}

While running I am getting following exception

"exceptionMessage": "Missing map from CategoriesAndBrandsServices.Models.Category to System.Collections.Generic.List1[CategoriesAndBrandsServices.Dtos.CategoryDto]. Create using Mapper.CreateMap<Category, List1>.", "exceptionType": "System.InvalidOperationException", "stackTrace": " at AutoMapper.QueryableExtensions.ExpressionBuilder.CreateMapExpression(ExpressionRequest request, Expression instanceParameter, IDictionary2 typePairCount)\r\n at AutoMapper.QueryableExtensions.ExpressionBuilder.CreateMapExpression(ExpressionRequest request, IDictionary2 typePairCount)\r\n at AutoMapper.QueryableExtensions.ExpressionBuilder.CreateMapExpression(ExpressionRequest request)\r\n at AutoMapper.LockingConcurrentDictionary2.<>c__DisplayClass2_1.<.ctor>b__1()\r\n at System.Lazy1.CreateValue()\r\n at System.Lazy1.LazyInitValue()\r\n at System.Lazy1.get_Value()\r\n at AutoMapper.LockingConcurrentDictionary2.GetOrAdd(TKey key)\r\n at AutoMapper.QueryableExtensions.ExpressionBuilder.CreateMapExpression(Type sourceType, Type destinationType, IDictionary2 parameters, MemberInfo[] membersToExpand)\r\n at AutoMapper.QueryableExtensions.ProjectionExpression.To[TResult](IDictionary2 parameters, IEnumerable1 memberPathsToExpand)\r\n at AutoMapper.QueryableExtensions.ProjectionExpression.To[TResult](Object parameters, Expression1[] membersToExpand)\r\n at AutoMapper.QueryableExtensions.Extensions.ProjectTo[TDestination](IQueryable source, IConfigurationProvider configuration, Object parameters, Expression1[] membersToExpand)\r\n at AutoMapper.QueryableExtensions.Extensions.ProjectTo[TDestination](IQueryable source, Expression1[] membersToExpand)\r\n at CategoriesAndBrandsServices.Controllers.CategoriesController.<Get>d__0.MoveNext() in c:\\OnlineShoppingWebsite\\Services\\CategoriesAndBrandsServices\\CategoriesAndBrandsServices\\Controllers\\CategoriesController.cs:line 24\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n at System.Threading.Tasks.TaskHelpersExtensions.d__31.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"

Upvotes: 0

Views: 1828

Answers (1)

Vova Bilyachat
Vova Bilyachat

Reputation: 19474

I assume that project to is one to one, and you try to cast from category to list of category dtos So try to repalce project to with this.

.ProjectTo<CategoryDto>()

PS. From exception "Missing map from CategoriesAndBrandsServices.Models.Category to System.Collections.Generic.List1[CategoriesAndBrandsServices.Dtos.CategoryDto]. Create using Mapper.CreateMap."

Upvotes: 1

Related Questions