问题
I'm mapping between two objects and based on a condition of the source I would like the destination to be null.
For example, here are the classes:
public class Foo
{
public int Code { get; set; }
public string Name { get; set; }
}
public class Bar
{
public string Name { get; set; }
public string Type { get; set; }
}
And my map:
Mapper.CreateMap<Foo, Bar>()
.AfterMap((s, d) => { if (s.Code != 0) d = null; });
But it seems to ignore the AfterMap. Bar is initialised although with all default properties.
How can I get the mapper to return null based on Code not being equal to 0?
Thanks
回答1:
One possible way is -
class Converter : TypeConverter<Foo, Bar>
{
protected override Bar ConvertCore(Foo source)
{
if (source.Code != 0)
return null;
return new Bar();
}
}
static void Main(string[] args)
{
Mapper.CreateMap<Foo, Bar>()
.ConvertUsing<Converter>();
var bar = Mapper.Map<Bar>(new Foo
{
Code = 1
});
//bar == null true
}
回答2:
I created the following extension method to solve this problem.
public static IMappingExpression<TSource, TDestination> PreCondition<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> mapping
, Func<TSource, bool> condition
)
where TDestination : new()
{
// This will configure the mapping to return null if the source object condition fails
mapping.ConstructUsing(
src => condition(src)
? new TDestination()
: default(TDestination)
);
// This will configure the mapping to ignore all member mappings to the null destination object
mapping.ForAllMembers(opt => opt.PreCondition(condition));
return mapping;
}
For the case in question, it can be used like this:
Mapper.CreateMap<Foo, Bar>()
.PreCondition(src => src.Code == 0);
Now, if the condition fails, the mapper will return null; otherwise, it will return the mapped object.
来源:https://stackoverflow.com/questions/34288574/automapper-set-destination-to-null-on-condition-of-source-property