-
Notifications
You must be signed in to change notification settings - Fork 26
Mapping
Umut Ozel edited this page May 8, 2017
·
7 revisions
- We can call Map with two generic parameters. We can override MapConfiguration's default option with preserveReferences.
public TOut Map<TIn, TOut>(TIn inObj, bool? preserveReferences = null)
// preserve references for this mapping, even when MapConfiguration's preserveReferences is false
var customerDto = config.Map<Customer, CustomerDTO>(customer, true);
- We can populate an existing target object.
public TOut MapTo<TIn, TOut>(TIn inObj, TOut outObj, bool? preserveReferences = null)
var customerDto = Session.Get<CustomerDto>(customer.Id);
customerDto = config.Map<Customer, CustomerDTO>(customer, customerDto);
- We can let BatMap to get the type of inObj.
public TOut Map<TOut>(object inObj, bool? preserveReferences = null)
var customerDto = config.Map<CustomerDTO>(customer);
- We can let BatMap figure out the target type. This method requires at least one registration for inObj's type.
public object Map(object inObj, bool? preserveReferences = null)
// BatMap will use the first match from registered mappings for inObj's type
var customerDto = config.Map(customer);
- We can explicitly tell BatMap the destination type. This method is useful when we can't use generic versions.
public object Map(object inObj, Type outType, bool? preserveReferences = null)
var customerDto = (CustomerDTO) config.Map(customer, typeof(CustomerDTO));
- We can Map whole IEnumerable<TIn>. This method will be faster than calling Map for each item in a loop. Because internally BatMap will get the MapDefinition for given types only once ⚡️
public IEnumerable<TOut> Map<TIn, TOut>(IEnumerable<TIn> source, bool? preserveReferences = null)
var customerDtos = config.Map<Customer, CustomerDTO>(customers);
- Like we did with IEnumerable, we can do the same for dictionaries too.
public Dictionary<TOutKey, TOutValue> Map<TInKey, TInValue, TOutKey, TOutValue>(
IDictionary<TInKey, TInValue> source, bool? preserveReferences = null)
// Customer will be mapped to CustomerDTO
var customerDtoDict = config.Map<int, Customer, int, CustomerDTO>(customerDict);
// This will work too. Keys will also be mapped when necessary
var customerDtoDict = config.Map<Customer, int, CustomerDTO, int>(customerDict);
Mapper static class has all of the above methods with only one difference:
public static IEnumerable<TOut> Map<TIn, TOut>(this IEnumerable<TIn> source, bool? preserveReferences = null)
customers.Map<Customer, CustomerDTO>();
It defines Map method as an extension method for IEnumerable<TIn> 💯
Developed with ❤️ at Doğuş Teknoloji