Skip to content

Query Mapping

Dima Bezzubenkov edited this page Sep 4, 2021 · 9 revisions

Query Mapping is a mapping type that injects EF Context into mapping expression, so you can write more advanced and optimized queries.

Query mapping is a function that takes 2 input arguments: source IQueryable instance and injected instance of EF Context. The returned expression describes how one model can be mapped to another model.

mappings.Add<Appartment, AppartmentReviewsModel, IDbContext>((query, context) =>
    from appartment in query
    join review in context.Set<Review>() on new { EntityId = appartment.Id, EntityTypeId = (int)EntityType.Appartment }
                                         equals new { EntityId = review.EntityId, EntityTypeId = review.EntityTypeId }
                                         into reviews
    select new AppartmentReviewsModel
    {
        Id = appartment.Id,
        Number = appartment.Number,
        Reviews = reviews.Select(review => new ReviewModel
        {
            Id = review.Id,
            EntityId = review.EntityId,
            EntityType = (EntityType)review.EntityTypeId,
            Rating = review.Rating,
            Comments = review.Comments
        }).ToList()
    });

In the previous example, the context of type IDbContext will be injected into the mapping function.

To inject context into your mapping you need to use a generic version of IQueryMappingService interface, where TContext is the type of context or interface that the context implements.

public MyService(IQueryMappingService<IDbContext> qmService)
{
    _qmService = qmService;
}
...
IQueryable<Appartments> query = ...;
var list = _qmService.AsQuery<Appartment, AppartmentReviewsModel>(query).ToList();