Search code examples
c#linqautomapperautomapper-6

How to trigger AutoMapper to map a model using linq syntax?


I am trying to use AutoMapper 6.3 to allow me to auto map my model into viewmodels.

First I registered my AutoMapper instance to my IUnitContainer like so

var mapper = new MapperConfiguration(cfg =>
{
    cfg.AddProfile<AutoMapperProfile>();
});

container.RegisterInstance<IMapper>(mapper.CreateMapper()); 

Now, in my controller, I want to pull a model from the database, then I want to map/cast it to my view-model.

I tried to do the following

var task = UnitOfWork.Tasks.Get(123)
                           .ProjectTo<TaskViewModel>();

But I can't seems to find the ProjectTo extension which I assumed it will be part of the AutoMapper project.

What is the correct way to project the viewModel if my AutoMapperProfile already created the mapping?


Solution

  • It seems to be in Automapper.QueryableExtensions:

    https://github.com/AutoMapper/AutoMapper/blob/8dd104aa7390c12c97c4195cce6f6ff66de24f51/src/AutoMapper/QueryableExtensions/Extensions.cs

    you can call it as long as the previous item in your linq change is IQueryable it seems.