Is it possible to call Mapper.Map inside AfterMap? - c#

Is something like this allowed somehow?
CreateMap<UserViewModel, User>()
.ForMember(u => u.Password, o => o.Ignore())
.AfterMap((src, dest) => {
...
var entity = Mapper.Map<Entity>(src.SomeProperty);
...
});
Is not working for me, it says that mapping tried to use inside AfterMap doesn't exist.

I notice that you are using the static AutoMapper class within your mapping, but are you also using the static instance outside of your mapping and does it have a mapping configured for your Entity class?
The below works, note that the context.Mapper call ensures that the same AutoMapper instance is used for both the calling Map and subsequent AfterMap methods.
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<UserViewModel, User>()
.AfterMap((source, destination, context) =>
{
var entity = context.Mapper.Map<Entity>(source.SomeProperty);
});
cfg.CreateMap<EntityViewModel, Entity>();
});
var mapper = config.CreateMapper();
var viewModel = new UserViewModel
{
Name = "Test User",
SomeProperty = new EntityViewModel
{
Value = "Sub Class"
}
};
var user = mapper.Map<User>(viewModel);

Related

Business Object to DTO conversion

I have a list of types of application. I want to transform that object to an object of type ApplicationDTO. Inside that Application business object, there is a list of Applicants of the type Applicant. Now my DTO has the same list but I am struggling with how to assign the list members of the business object to the list inside the DTO. I have had multiple such occurrences where it is not known how many items I have on the list.
Here is an example:
// List of business objects
List<Application> ApplicationList = await _dbContextDigitVP.Applications.FromSqlRaw("Exec dbo.GetApplication {0}", id).ToListAsync();
//DTO object
ApplicationDTO applicationDTO = new ApplicationDTO
{
ApplicationNumber = Application.ApplicationNumber,
Country = Application.Country,
ApplicationUuid = Application.ApplicationUuid,
PwEmployeeAdUserName = Application.PwEmployeeAdUserName,
Category = new ApplicationCategoryDTO
{
Category = Application.Category?.Category
},
Applicants = new List<ApplicantDTO>()
{
// add members of the business object
}
};
I could go over it with a for loop but is there a way to do this inside the object definition?
You can use AutoMapper.
Once you have your types you can create a map for the two types using a MapperConfiguration and CreateMap. You only need one MapperConfiguration instance typically per AppDomain and should be instantiated during startup.
var config = new MapperConfiguration(cfg => cfg.CreateMap<Application,
ApplicationDTO>());
The type on the left is the source type, and the type on the right is the destination type. To perform a mapping, call one of the Map overloads:
var mapper = config.CreateMapper();
// or
var mapper = new Mapper(config);
ApplicationDTO dto = mapper.Map<ApplicationDTO>(Application);
you can also use LINQ to transform objects like without using AutoMapper.
List<ApplicationDTO> applicationDTOList = ApplicationList.Select(app => new ApplicationDTO
{
ApplicationNumber = app.ApplicationNumber,
Country = app.Country,
ApplicationUuid = app.ApplicationUuid,
PwEmployeeAdUserName = app.PwEmployeeAdUserName,
Category = new ApplicationCategoryDTO
{
Category = app.Category?.Category
},
Applicants = app.Applicants.Select(a => new ApplicantDTO
{
// same logic as the above
}).ToList()
}).ToList();
You can use Automapper to map data from one object to another.
Create Automapper configurations like this for the configure mapping between the ApplicationDTO and Application, ApplicationCategory and ApplicationCategoryDTO and Applicant to ApplicantDTO
var configuration = new MapperConfiguration(cfg => {
//Source ==> Desti
//Application and ApplicationDTO classes
cfg.CreateMap < Application, ApplicationDTO > ()
.ForMember(dest => dest.Category, opt => opt.MapFrom(src => src.Category))
.ForMember(dest => dest.Applicants, opt => opt.MapFrom(src => src.Applicants));
//ApplicationCategory and ApplicationCategoryDTO classes
cfg.CreateMap < ApplicationCategory, ApplicationCategoryDTO > ();
//Applicant and ApplicantDTO classes
cfg.CreateMap < Applicant, ApplicantDTO > ();
});
In your constructor, you can initialize Mapper like
private readonly IMapper _Mapper;
public TestController(IMapper mapper) {
_Mapper = mapper;
}
When you doing the casting you can do somthing like this,
var applicationDTOList = _Mapper.Map<List<ApplicationDTO>>(ApplicationList);

Is there a way to pass destination object to ForAllMembers method of AutoMapperProfile object

I am just learning how to use AutoMapper utility.
Below is my AutoMapperProfile class. Here is how I call my mapper to map model object to user object:
var user = _mapper.Map<User>(model);
I would like to initialize my destination object(user) with some properties before calling var user = _mapper.Map<User>(model);. Then I would like to call the mapper var user = _mapper.Map<User>(model); and pass the user object to the ForAllMembers (from the code below - see AutoMapperProfile) and preserve those initialized properties during mapping process. The problem I have is that when ForAllMembers is called my destination object has all properties set to null initially. Is there a way to pass that object to ForAllMembers t?
using AutoMapper;
using coreapi.requests;
namespace WebApi.Helpers
{
public class AutoMapperProfile : Profile
{
// mappings between model and entity objects
public AutoMapperProfile()
{
CreateMap<UserRequest, User>()
.ForMember(dst => dst.Blah, o => o.MapFrom(src => src.Test))
.ForAllMembers(x => x.Condition(
(src, dest, prop) =>
{
// ignore null role
if (x.DestinationMember.Name == "Blah" && src.Test == null)
return false;
return true;
}
));
}
}
}

Can't access automapper context items after upgrade to 9

I have a mapper like this:
CreateMap<Source, ICollection<Dest>>()
.ConvertUsing((src, dst, context) =>
{
return context.Mapper.Map<ICollection<Dest>>
(new SourceItem[] { src.Item1, src.Item2 ... }.Where(item => SomeFilter(item)),
opts => opts.Items["SomethingFromSource"] = src.Something);
});
CreateMap<SourceItem, Dest>()
.ForMember(d => d.Something, opts => opts.MapFrom((src, dst, dstItem, context)
=> (string)context.Items["SomethingFromSource"]));
This gives me an exception saying You must use a Map overload that takes Action<IMappingOperationOptions>. Well, I do use the Map overload that takes this action. How else can I do this?
This is because of this change:
https://github.com/AutoMapper/AutoMapper/pull/3150
You can get the the Items by accessing the ResolutionContext's Options property.
Change context.Items["SomethingFromSource"] to context.Options.Items["SomethingFromSource"].
When there is no Items, the ResolutionContext is the same with DefaultContext. Therefore The ResolutionContext.Items property will throw the exception.
However, if there is, the ResolutionContext.Items wouldn't be the same with DefaultContext. Therefore the ResolutionContext.Items will return the list.
While ResolutionContext.Options.Items will always return the list, it would not throw any exception, whether it's empty or not. I believe it's what the error message meant, because ResolutionContext.Options is an IMappingOperationOptions
This extension can help with migrating to AutoMapper 12
public static class AutoMapperExtensions
{
public static TDestination MapOptions<TDestination>(this IMapper mapper, object source, Action<IMappingOperationOptions<object, TDestination>> OptionalOptions = null)
{
return mapper.Map(source, OptionalOptions ?? (_ => {}) );
}
}
In a Class where IMapper has been injected
public class Command
{
protected readonly IMapper AutoMapper;
public Command(IMapper mapper)
{
AutoMapper = mapper;
}
private SomethingToDo()
{
var list = new List<string>();
// change for 12
var result = AutoMapper.MapOptions<IList<Item>>(list);
// prior to 12
//var result = AutoMapper.Map<IList<Item>>(list);
}
}
Several points of consideration when you use inner mapper (i.e. context.Mapper)
First, try not to use context.Mapper.Map<TDestination>(...), use context.Mapper.Map<TSource, TDestination>(...) instead, it behaves much better.
Second, use of context in inner mappers will break encapsulation. If you need to set the values in inner objects, consider these two solutions:
In case you want to set the values after the inner map
context.Mapper.Map<Source, Dest> (source, opts => opts.AfterMap((s, d) =>
d.Something = source.Something))
In case you want to set the values before the inner map
context.Mapper.Map<Source, Dest> (source, new Dest()
{
Something = source.Something
})

ASP.NET Core with EF Core - DTO Collection mapping

I am trying to use (POST/PUT) a DTO object with a collection of child objects from JavaScript to an ASP.NET Core (Web API) with an EF Core context as my data source.
The main DTO class is something like this (simplified of course):
public class CustomerDto {
public int Id { get;set }
...
public IList<PersonDto> SomePersons { get; set; }
...
}
What I don't really know is how to map this to the Customer entity class in a way that does not include a lot of code just for finding out which Persons had been added/updated/removed etc.
I have played around a bit with AutoMapper but it does not really seem to play nice with EF Core in this scenario (complex object structure) and collections.
After googling for some advice around this I haven't found any good resources around what a good approach would be. My questions is basically: should I redesign the JS-client to not use "complex" DTOs or is this something that "should" be handled by a mapping layer between my DTOs and Entity model or are there any other good solution that I am not aware of?
I have been able to solve it with both AutoMapper and and by manually mapping between the objects but none of the solutions feels right and quickly become pretty complex with much boilerplate code.
EDIT:
The following article describes what I am referring to regarding AutoMapper and EF Core. Its not complicated code but I just want to know if it's the "best" way to manage this.
(Code from the article is edited to fit the code example above)
http://cpratt.co/using-automapper-mapping-instances/
var updatedPersons = new List<Person>();
foreach (var personDto in customerDto.SomePersons)
{
var existingPerson = customer.SomePersons.SingleOrDefault(m => m.Id == pet.Id);
// No existing person with this id, so add a new one
if (existingPerson == null)
{
updatedPersons.Add(AutoMapper.Mapper.Map<Person>(personDto));
}
// Existing person found, so map to existing instance
else
{
AutoMapper.Mapper.Map(personDto, existingPerson);
updatedPersons.Add(existingPerson);
}
}
// Set SomePersons to updated list (any removed items drop out naturally)
customer.SomePersons = updatedPersons;
Code above written as a generic extension method.
public static void MapCollection<TSourceType, TTargetType>(this IMapper mapper, Func<ICollection<TSourceType>> getSourceCollection, Func<TSourceType, TTargetType> getFromTargetCollection, Action<List<TTargetType>> setTargetCollection)
{
var updatedTargetObjects = new List<TTargetType>();
foreach (var sourceObject in getSourceCollection())
{
TTargetType existingTargetObject = getFromTargetCollection(sourceObject);
updatedTargetObjects.Add(existingTargetObject == null
? mapper.Map<TTargetType>(sourceObject)
: mapper.Map(sourceObject, existingTargetObject));
}
setTargetCollection(updatedTargetObjects);
}
.....
_mapper.MapCollection(
() => customerDto.SomePersons,
dto => customer.SomePersons.SingleOrDefault(e => e.Id == dto.Id),
targetCollection => customer.SomePersons = targetCollection as IList<Person>);
Edit:
One thing I really want is to delcare the AutoMapper configuration in one place (Profile) not have to use the MapCollection() extension every time I use the mapper (or any other solution that requires complicating the mapping code).
So I created an extension method like this
public static class AutoMapperExtensions
{
public static ICollection<TTargetType> ResolveCollection<TSourceType, TTargetType>(this IMapper mapper,
ICollection<TSourceType> sourceCollection,
ICollection<TTargetType> targetCollection,
Func<ICollection<TTargetType>, TSourceType, TTargetType> getMappingTargetFromTargetCollectionOrNull)
{
var existing = targetCollection.ToList();
targetCollection.Clear();
return ResolveCollection(mapper, sourceCollection, s => getMappingTargetFromTargetCollectionOrNull(existing, s), t => t);
}
private static ICollection<TTargetType> ResolveCollection<TSourceType, TTargetType>(
IMapper mapper,
ICollection<TSourceType> sourceCollection,
Func<TSourceType, TTargetType> getMappingTargetFromTargetCollectionOrNull,
Func<IList<TTargetType>, ICollection<TTargetType>> updateTargetCollection)
{
var updatedTargetObjects = new List<TTargetType>();
foreach (var sourceObject in sourceCollection ?? Enumerable.Empty<TSourceType>())
{
TTargetType existingTargetObject = getMappingTargetFromTargetCollectionOrNull(sourceObject);
updatedTargetObjects.Add(existingTargetObject == null
? mapper.Map<TTargetType>(sourceObject)
: mapper.Map(sourceObject, existingTargetObject));
}
return updateTargetCollection(updatedTargetObjects);
}
}
Then when I create the mappings I us it like this:
CreateMap<CustomerDto, Customer>()
.ForMember(m => m.SomePersons, o =>
{
o.ResolveUsing((source, target, member, ctx) =>
{
return ctx.Mapper.ResolveCollection(
source.SomePersons,
target.SomePersons,
(targetCollection, sourceObject) => targetCollection.SingleOrDefault(t => t.Id == sourceObject.Id));
});
});
Which allow me to use it like this when mapping:
_mapper.Map(customerDto, customer);
And the resolver takes care of the mapping.
AutoMapper is the best solution.
You can do it very easily like this :
Mapper.CreateMap<Customer, CustomerDto>();
Mapper.CreateMap<CustomerDto, Customer>();
Mapper.CreateMap<Person, PersonDto>();
Mapper.CreateMap<PersonDto, Person>();
Note : Because AutoMapper will automatically map the List<Person> to List<PersonDto>.since they have same name, and there is already a mapping from Person to PersonDto.
If you need to know how to inject it to ASP.net core,you have to see this article : Integrating AutoMapper with ASP.NET Core DI
Auto mapping between DTOs and entities
Mapping using attributes and extension methods
First I would recommend using JsonPatchDocument for your update:
[HttpPatch("{id}")]
public IActionResult Patch(int id, [FromBody] JsonPatchDocument<CustomerDTO> patchDocument)
{
var customer = context.EntityWithRelationships.SingleOrDefault(e => e.Id == id);
var dto = mapper.Map<CustomerDTO>(customer);
patchDocument.ApplyTo(dto);
var updated = mapper.Map(dto, customer);
context.Entry(entity).CurrentValues.SetValues(updated);
context.SaveChanges();
return NoContent();
}
And secound you should take advantage of AutoMapper.Collections.EFCore. This is how I configured AutoMapper in Startup.cs with an extension method, so that I´m able to call services.AddAutoMapper() without the whole configuration-code:
public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddCollectionMappers();
cfg.UseEntityFrameworkCoreModel<MyContext>(services);
cfg.AddProfile(new YourProfile()); // <- you can do this however you like
});
IMapper mapper = config.CreateMapper();
return services.AddSingleton(mapper);
}
This is what YourProfile should look like:
public YourProfile()
{
CreateMap<Person, PersonDTO>(MemberList.Destination)
.EqualityComparison((p, dto) => p.Id == dto.Id)
.ReverseMap();
CreateMap<Customer, CustomerDTO>(MemberList.Destination)
.ReverseMap();
}
I have a similar object-graph an this works fine for me.
EDIT
I use LazyLoading, if you don´t you have to explicitly load navigationProperties/Collections.
I was struggling with the very same issue for quite some time. After digging through many articles I've came up with my own implementation which I'm sharing with you.
First of all I've created a custom IMemberValueResolver.
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutoMapper
{
public class CollectionValueResolver<TDto, TItemDto, TModel, TItemModel> : IMemberValueResolver<TDto, TModel, IEnumerable<TItemDto>, IEnumerable<TItemModel>>
where TDto : class
where TModel : class
{
private readonly Func<TItemDto, TItemModel, bool> _keyMatch;
private readonly Func<TItemDto, bool> _saveOnlyIf;
public CollectionValueResolver(Func<TItemDto, TItemModel, bool> keyMatch, Func<TItemDto, bool> saveOnlyIf = null)
{
_keyMatch = keyMatch;
_saveOnlyIf = saveOnlyIf;
}
public IEnumerable<TItemModel> Resolve(TDto sourceDto, TModel destinationModel, IEnumerable<TItemDto> sourceDtos, IEnumerable<TItemModel> destinationModels, ResolutionContext context)
{
var mapper = context.Mapper;
var models = new List<TItemModel>();
foreach (var dto in sourceDtos)
{
if (_saveOnlyIf == null || _saveOnlyIf(dto))
{
var existingModel = destinationModels.SingleOrDefault(model => _keyMatch(dto, model));
if (EqualityComparer<TItemModel>.Default.Equals(existingModel, default(TItemModel)))
{
models.Add(mapper.Map<TItemModel>(dto));
}
else
{
mapper.Map(dto, existingModel);
models.Add(existingModel);
}
}
}
return models;
}
}
}
Then I configure AutoMapper and add my specific mapping:
cfg.CreateMap<TDto, TModel>()
.ForMember(dst => dst.DestinationCollection, opts =>
opts.ResolveUsing(new CollectionValueResolver<TDto, TItemDto, TModel, TItemModel>((src, dst) => src.Id == dst.SomeOtherId, src => !string.IsNullOrEmpty(src.ThisValueShouldntBeEmpty)), src => src.SourceCollection));
This implementation allows me to fully customize my object matching logic due to keyMatch function that is passed in constructor. You can also pass an additional saveOnlyIf function if you for some reason need to verify passed objects if they are suitable for mapping (in my case there were some objects that shouldn't be mapped and added to collection if they didn't pass an extra validation).
Then e.g. in your controller if you want to update your disconnected graph you should do the following:
var model = await Service.GetAsync(dto.Id); // obtain existing object from db
Mapper.Map(dto, model);
await Service.UpdateAsync(model);
This works for me. It's up to you if this implementation suits you better than what author of this question proposed in his edited post:)

Automapper returning an empty collection, I want a null

public class Person
{
Name { get; set; }
IEnumerable<Address> Addresses { get; set; }
}
public class PersonModel
{
Name { get; set; }
IEnumerable<AddressModel> Addresses { get; set; }
}
If I map Person to PersonModel like so:
Mapper.DynamicMap<Person, PersonModel>(person);
If the Addresses property on Person is null they are mapped on PersonModel as an empty Enumerable instead of null.
How do I get PersonModel to have null Addresses instead of an empty Enumerable?
The simple answer is to use AllowNullCollections:
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.AllowNullCollections = true;
});
or if you use the instance API
new MapperConfiguration(cfg =>
{
cfg.AllowNullCollections = true;
}
In addition to setting AllowNullCollections in the mapper configuration initialization (as noted in this answer), you have the option to set AllowNullCollections in your Profile definition, like this:
public class MyMapper : Profile
{
public MyMapper()
{
// Null collections will be mapped to null collections instead of empty collections.
AllowNullCollections = true;
CreateMap<MySource, MyDestination>();
}
}
So there are probably several ways you can accomplish this with Automapper, and this is just one:
Mapper.CreateMap<Person, PersonMap>()
.AfterMap( (src, dest) => dest.Addresses = dest.Addresses?.Any() ? dest.Addresses : null );
This code uses the new c# ?. operator for null safety, so you might need to remove that and check for null if you can't use that feature in your code.
Another alternative to this is to use a condition, so only map the value when the value is not null.
This may require that the value default to null (as it wont be mapped)
Mapper.CreateMap<Person, PersonModel>()
.ForMember(
dest => dest.Addresses,
opt => opt => opt.Condition(source=> source.Addresses!= null));
You should be able to define a custom resolver for the property you want this behaviour on. So something like:
Mapper.CreateMap<Address, AddressModel>();
Mapper.CreateMap<Person, PersonModel>()
.ForMember(
dest => dest.Addresses,
opt => opt.ResolveUsing(person => person.Addresses.Any() ? person.Addresses.Select(Mapper.Map<Address, AddressModel>) : null));
if you want this as a general rule in your API, you could configure Automapper in the configure services method like this.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
[...]
// configure automapping
services.AddAutoMapper(cfg => cfg.AllowNullCollections = true, typeof(Startup));
}
Or, in the case of using Automapping in a separate DLL (example: for DTO services), I prefer to use a helper function, so the configuration should be done there too:
public static class MappingHelper
{
private static readonly Lazy<IMapper> _lazy = new(() =>
{
var config = new MapperConfiguration(cfg =>
{
// This line ensures that internal properties are also mapped over.
cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
cfg.AddProfile<DomainToRepositoryProfile>();
cfg.AddProfile<RepositoryToDomainProfile>();
cfg.AllowNullCollections = true;
});
var mapper = config.CreateMapper();
return mapper;
});
public static IMapper Mapper => _lazy.Value;
}

Categories

Resources