X.Otano
X.Otano

Reputation: 2179

AutoMapper: How to map between Linq Expressions (Func<>)

I am using repository pattern, so my repository just know about DTOs. It has to query the database with some filters using Entity Framework. My problem is that Entity Framework only knows about DB model classes, so I have to 'automap' the Expression before being able to use them in any query.

I have declared a method that accepts a Expression as a filter.

public interface IRepository
{
    IEnumerable<ItemDTO> GetItemsWithFilter(Expression<Func<ItemDTO, bool>> filter)
    {
        var filterDb = Mapper.Map<Expression<Func<ItemDB, bool>>>(filter);
        return dbContext.CONFIGURATIONS.Where(filterDb).Select(x => Mapper.Map<ItemDTO>(x));
    }
}

public class ItemDTO
{
   public int numero { get; set; }
   public string name { get; set; }
} 

public class ItemDB //they are both the same, just for testing purpose
{
   public int numero { get; set; }
   public string name { get; set; }
}

//failing code 
 Repository.GetItemsWithFilter(x => x.name=="a");

I followed tutorial that says it is possible to map between expressions but i get some errors:

"The specified type member 'name' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."}

Upvotes: 1

Views: 1572

Answers (1)

X.Otano
X.Otano

Reputation: 2179

I solved it by including this extension method call:

 Mapper.Initialize(cfg => {
    cfg.AddExpressionMapping();
    // Rest of your configuration
 });

Remeber to install nuget package AutoMapper.Extensions.ExpressionMapping

Install-Package AutoMapper.Extensions.ExpressionMapping

Upvotes: 5

Related Questions