Skip to content

Named Mappings

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

In some cases you will need more than one way to map one model to another. In this case direction of mapping (From -> To) is not enough to resolve correct mapping. You can give names to the mappings and use this names when you apply mapping to IQueryable instance:

mappings.Add<Address, AddressSummaryModel>(MappingsNames.ExtendedAddressFormat, x => new AddressSummaryModel
{
    Id = x.Id,
    Address = x.BuildingNumber + " " + x.Street + ", " + x.City + ", " + x.State + ", " + x.Country + ", " + x.ZipCode
});

mappings.Add<Address, AddressSummaryModel>(MappingsNames.ShortAddressFormat, x => new AddressSummaryModel
{
    Id = x.Id,
    Address = x.BuildingNumber + " " + x.Street + ", " + x.City 
});

IQueryable<Address> query = ...;
var list = _qmService.AsQuery<Address, AddressSummaryModel>(MappingsNames.ShortAddressFormat).ToList();

Every type of mapping can be registered as Named Mapping and every overload of AsQuery method takes additional non-required argument "name".

In general this situation happens quite seldom. Usually different models will have at least some minor differences and it's always a good idea to create 2 different models in this case (and maybe inherit one model from another).

Use Named mappings only when models are actually the same and create new models even if they are different at least by 1 field.