I'm already successfully using AutoMapper
in my ASP.NET Core application. I'm creating mapping configurations and mostly use ForMember
, BeforeMap
or AfterMap
to customize certain mappings.
Now I have a particular scenario in which I import data and I update an existing entity if it exists or create a new if it doesn't. I would like to also use AutoMapper
to map entities.
For example (kept simple) I have an import class:
public class ImportModel
{
public int Number { get; set; }
public string Description { get; set; }
}
And the actual model class:
public class ActualModel
{
public int Id { get; set; }
public int Number { get; set; }
public string Description { get; set; }
}
As I parse and iterate through the import rows I currently do:
var model = modelService.Get(x => x.Number == item.Number);
if (model != null)
{
model.Description = item.Description ;
}
else
{
model = new ActualModel() {
Number = item.Number,
Description = item.Description
};
}
Now, basically I would like to change the above into (hopefully) a single line using a mapping configuration to add/update a model.
Is it possible to achieve this (maybe using additional AutoMapper
features customer resolvers, construcstors, etc)?
CodePudding user response:
The overload
destination = mapper.Map<TSource, TDestination>(source, destination);
does the trick.