First of all, sorry for my bad english! I'm french.
I tried to find on google but without any result so, this is my automapper configuration :
public void CreateMap(IMapperConfiguration cfg)
{
cfg.CreateMap<GroupeApplication, GroupeApplicationContract>();
cfg.CreateMap<Application, ApplicationContract>()
.ForMember(d => d.GroupeApplicationId, o => o.MapFrom(s => s.GroupeApplication != null ? s.GroupeApplication.Id : Guid.Empty));
cfg.CreateMap<Application, ApplicationWithAscendantContract>()
.ForMember(d => d.GroupeApplication, o => o.MapFrom(s => Mapper.Map<GroupeApplicationContract>(s.GroupeApplication)));
cfg.CreateMap<GroupeApplication, GroupeApplicationWithDescendantContract>()
.ForMember(d => d.Applications, o => o.MapFrom(s => Mapper.Map<List<ApplicationContract>>(s.Applications)));
Mapper.AssertConfigurationIsValid();
}
In fact, groupeapplication has list of application, and Mapper.Map failed when it try to map my applications collection... this is the error message :
Missing type map configuration or unsupported mapping.
Mapping types:
Application -> ApplicationContract
UGO.Distribution.Domain.Application -> UGO.Distribution.Shared.Contracts.ApplicationContract
Destination path:
List`1[0]
Source value:
UGO.Distribution.Domain.Application
If I replace the last config with this it works (I replace Mapper.Map by Mapper.DynamicMap) :
cfg.CreateMap<GroupeApplication, GroupeApplicationWithDescendantContract>()
.ForMember(d => d.Applications, o => o.MapFrom(s => Mapper.DynamicMap<List<ApplicationContract>>(s.Applications)));
I could be satisfied, but that is not for me is that this method is deprecated in automapper 4.0.3 !!
Is there any explanation or a better solution for this problem?
Instead of putting ForMember(...), try:
ForMember<ObjectThatYouWantMap>(...);
Related
I'm fairly new to AutoMapper and want to know how to set a destination member to a value based on a DIFFERENT source property value and if that value is null I just want to apply the default behaviour of Automapper (keep destination value when the source is null)
CreateMap<ClassA, ClassA>()
.ForMember(dest => dest.PropertyA, opt =>
opt.MapFrom(src => src.PropertyB!= null ? null : opt.UseDestinationValue())
)
This doesn't work (don't compile) the opt.UseDestinationValue() , what option can I use here?
Please help
Try setting a precondition for mapping destination property.
CreateMap<ClassA, ClassA>().ForMember(dest => dest.PropertyA, opt => opt.PreCondition((src, dest) => src.PropertyB != null));
This will map PropertyA only when PropertyB is not null. I did try a quick sample which gave the desired result.
I think you can use the PreCondition option For Mapping Property
CreateMap<ClassA, ClassA>()
.ForMember(dest => dest.PropertyA, opt => {
opt.PreCondition(src => src.PropertyB!= null);
opt.MapFrom(src => src.PropertyB);
});
Hope to help you
You can do as follows:
var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<ClassA,ClassA>()
.ForMember(dest => dest.PropertyA, opt => opt.Condition(src => (src.PropertyB!= null)));
});
Or as follows:
var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<ClassA,ClassA>()
.ForMember(dest => dest.PropertyA, opt => {
opt.PreCondition(src => (src.PropertyB!=null));
opt.MapFrom(src => src.PropertyB); // mapping process takes place here
});
});
But the difference is that, the later runs sooner in the mapping process.
There is an excellent documentation in setting conditions for automapper:
https://docs.automapper.org/en/stable/Conditional-mapping.html
I have the two distinct objects and would like to map them to one destination object. The source objects are complex objects which contain multiple child objects which would also need to be mapped. I've tried something similar to the below example but as expected, the last mapping will overwrite any previous mapping.
CreateMap<sourceObject, destinationObject>()
.ForMember(d => d.Addresses, o => o.MapFrom(s => s.Addresses.MainAddresses))
.ForMember(d => d.Addresses, o => o.MapFrom(s => s.Addresses.SomeOtherAddresses))
I suppose I'm looking for something like a MapFrom().AndThenMapFrom() method (a join or union type transformation).
I have used a custom value resolver to get around the issue but this seems to defeat the purpose of automapper in my eyes. Any other suggestions would be welcomed.
If you want to concatenate in Addresses results of mappings (MainAddresses to Addresses and SomeOtherAddresses to Addresses), one solution would be
CreateMap<sourceObject, destinationObject>()
.ForMember(
d => d.Addresses,
o => o.MapFrom(
s => s.Addresses.MainAddresses
.Cast<object>()
.Concat(s.Addresses.SomeOtherAddresses)))
or
CreateMap<sourceObject, destinationObject>()
.ForMember(
d => d.Addresses,
o => o.MapFrom(
s => s.Addresses.MainAddresses
.Cast<IAddress>()
.Concat(s.Addresses.SomeOtherAddresses)))
if objects in MainAddresses and SomeOtherAddresses realize IAddress interface.
Another solution is to do it in Before/AfterMap method
CreateMap<sourceObject, destinationObject>()
.BeforeMap(
(s, d, c) =>
{
var mainAddresses = c.Mapper.Map<IEnumerable<Address>>(s.Addresses.MainAddresses);
var someOtherAddresses = c.Mapper.Map<IEnumerable<Address>>(s.Addresses.SomeOtherAddresses);
d.Addresses = mainAddresses
.Concat(someOtherAddresses)
.ToArray();
})
.ForMember(d => d.Addresses, o => o.Ignore());
In this case mapping for Addresses should be ignored, because we do it "manually" in BeforeMap. Unfortunately both solutions are not elegant as most of simple automapper rules.
Is it possible to use a custom value resolver in automapper only if a certain condition is met?
In my case I only want to update the value with the custom value resolver if the destination is not null.
This is an example of my code. Basically I need to add the condition onto this. Is it possible?
Mapper.CreateMap<ResponseXml, MyModel>()
.ForMember(dest => dest.FirstName,
op => op.ResolveUsing<ResponseXmlValueResolver>()
.FromMember(x => x.data.FirstOrDefault(y => y.name == "name")))
I think Eris' solution would have work; It was just grammatical errors.
Mapper.CreateMap<ResponseXml, MyModel>()
.ForMember(dest => dest.FirstName,
op => {
op.Condition(src => src != null);
op.ResolveUsing<ResponseXmlValueResolver>();
.FromMember(x => x.data.FirstOrDefault(y => y.name == "name"));
});
Is this what you wanted?
If the destination is null, the mapping will be ignore.
If the destination is null, the mapping (with the customer resolved) will be apply.
As Conditions are evaluated after resolving member, like it's said here, none of the previous answers are correct.
You should rather use PreCondition this way:
Mapper.CreateMap<ResponseXml, MyModel>()
.ForMember(dest => dest.FirstName,
op => {
op.PreCondition(src => src != null);
op.ResolveUsing<ResponseXmlValueResolver>();
.FromMember(x => x.data.FirstOrDefault(y => y.name == "name"));
});
Will this work? (I don't have a windows box in front of me at the moment)
Mapper.CreateMap<ResponseXml, MyModel>()
.ForMember(dest => dest.FirstName,
op => op.Condition(src => src != null)
.ResolveUsing<ResponseXmlValueResolver>()
.FromMember(x => x.data.FirstOrDefault(y => y.name == "name")))
I'm using automapper and I would like to know if it's possible to ignore a mapping of a field when that's null.
That's my code:
.ForMember(dest => dest.BusinessGroup_Id,
opt => opt.MapFrom(src => (int)src.BusinessGroup))
src.BusinessGroup type = "enum"
dest.BusinessGroup_Id = int
The objective it's to ingore that Mapping if src.BusinessGroup = null.
I think NullSubstitute option will do the trick
.ForMember(d => d.BusinessGroup_Id, o => o.MapFrom(s => (int?)s.BusinessGroup));
.ForMember(d => d.BusinessGroup_Id, o => o.NullSubstitute(0));
BTW you can write your conditions in mapping action:
.ForMember(d => d.BusinessGroup_Id,
o => o.MapFrom(s => s.BusinessGroup == null ? 0 : (int)s.BusinessGroup));
UPDATE if you cannot assign some default value to your property, you can just ignore it and map only not nulls:
.ForMember(d => d.BusinessGroup_Id, o => o.Ignore())
.AfterMap((s, d) =>
{
if (s.BusinessGroup != null)
d.BusinessGroup_Id = (int)s.BusinessGroup;
});
This question already has answers here:
AutoMapper: "Ignore the rest"?
(20 answers)
Closed 6 years ago.
Is there a way to do this? We have a SummaryDto that maps from three different types, and when we create a map for each type, props that are not mapped are throwing an error. There are about 35 attributes on the summary dto. To use Ignore() option on each one is just too much trouble. Is there a global ignore? Something like
CreateMap<Source,Target>()
.IgnoreAllUnmapped();
This is working for me:
public static class MappingExpressionExtensions
{
public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
{
expression.ForAllMembers(opt => opt.Ignore());
return expression;
}
}
Because ForAllMembers returns void, calling ForAllMembers(o => o.Ignore()) without this extension method wouldn't work. We want to keep the mapping expression available to enable the subsequent mappings:
CreateMap<Source, Destination>()
.IgnoreAllUnmapped()
.ForMember(d => d.Text, o => o.MapFrom(s => s.Name))
.ForMember(d => d.Value, o => o.MapFrom(s => s.Id));
I struggled with this one for quite a while too, or at least a problem similar to this. I had a class with a lot of properties on it (about 30) and I only wanted to map about 4 of them. It seems crazy to add 26 ignore statements (especially when it means that future changes to the class will mean having to update them!)
I finally found that I could tell AutoMapper to ignore everything, and then explicitly add the ones that I did want.
// Create a map, store a reference to it in a local variable
var map = CreateMap<Source,Target>();
// Ignore all members
map.ForAllMembers(opt => opt.Ignore());
// Add mapping for P1
map.ForMember(dest => dest.P1, opt => opt.MapFrom( src => src.P1));
// Add other mappings...
map.ForMember(dest => dest.P2, opt => opt.MapFrom( src => src.P2));
map.ForMember(dest => dest.P3, opt => opt.MapFrom( src => src.P3));
map.ForMember(dest => dest.P4, opt => opt.MapFrom( src => src.P4));
You'd be forgiven for thinking that you could just do this (but don't because it wont compile):
// This won't compile
CreateMap<Source,Target>()
.ForAllMembers(opt => opt.Ignore())
.ForMember(dest => dest.P1, opt => opt.MapFrom( src => src.P1));
The reason why this doesn't work is that the ForAllMembers() method doesn't support the fluent style of chaining (at least in the current version 2.0).
The good news is that the non-chaining version does indeed work. The one caveat of course is that you need to explicitly tell AutoMapper which members to map. I haven't yet found an easy way to have it both ways so that you can still use the implied mappings and ignore the broken ones.
To avoid having to explicitly specify the mapped properties, you can use IgnoreAllNonExisting. It ignores any destination properties that don't have mapped source properties.
Try to use .ConvertUsing() in your case, e.g.
CreateMap<Source,Target>()
.ConvertUsing(converter=> new Target(){
P1 = converter.P1,
....
});
So, you can describe all properties what you want to have in your object, other will be ignored.
Extension method which allows fluent syntax for the ForAllMembers method:
public static IMappingExpression<TSource, TDestination> IgnoreAllMembers<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> expression
)
{
expression.ForAllMembers(opt => opt.Ignore());
return expression;
}
Usage:
The call to IgnoreAllMembers must be before the call to ForMember.
CreateMap<LocationRevision, Dto.LocationAddressMap>()
.IgnoreAllMembers()
.ForMember(m => m.LocationId, opt => opt.MapFrom(src => src.Id))
;