CaptnKebec
CaptnKebec

Reputation: 31

Using automapper with dynamic linq and order by clause

I'm using automapper for a dynamic query and it's working well until I use an orderby clause. So this is how I create the query:

IQueryable<DTOFormCellSouches> query;
//Configuration de l'automapper de l'objet BD vers le DTO
var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<FormCellSouch, DTOFormCellSouches>();
});
//Map des champs
var mapper = config.CreateMapper();

query = (_context.FormCellSouches).Select(a => mapper.Map<FormCellSouch, DTOFormCellSouches>(a));

return query;

Then if I have an order criteria, I add it to the querylike this:

if (orderCriteria != "")
{
    if (query != null)
    {
        query = query.OrderBy(orderCriteria);
    }
}

I get that error when adding the criteria and running the query: The LINQ expression 'DbSet() .OrderBy(f => __mapper_0.Map<FormCellSouch, DTOFormCellSouches>(f).Nom)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

Since it's dynamic, it can have filter too, so there will be where clause and I'll probably have a similar problem.

I've tried to convert the query to other format has the message suggest but I can't make it work.

Upvotes: 0

Views: 18

Answers (1)

CaptnKebec
CaptnKebec

Reputation: 31

I found a way, just adding ToList().AsQueryable(), resolved the issue:

I change my query line with the following: query = (_context.FormCellSouches).Select(a => mapper.Map<FormCellSouch, DTOFormCellSouches>(a)).ToList().AsQueryable();

Upvotes: 0

Related Questions