Reputation: 26290
I'm defining a mapping between a source class and a target class:
Mapper.CreateMap<Source, Target>();
I want the mapping to return null
if a certain property on the Source
is set to a particular value:
// If Source.IsValid = false I want the mapping to return null
Source s = new Source { IsValid = false };
Target t = Mapper.Map<Target>(s);
Assert.IsNull(t);
How do I configure AutoMapper to achieve that?
Upvotes: 3
Views: 4072
Reputation: 26290
You can define your mapping like this:
Mapper.CreateMap<Source, Target>().TypeMap
.SetCondition(r => ((Source)r.SourceValue).IsValid);
Upvotes: 3
Reputation: 14962
EDIT
If you want your map to output a null object I'd recommend using two levels of mapping: the first level decides whether or not to return a null object by taking over mapping behavior with the ConvertUsing
method, and if mapping is required it defers it to an inner mapping engine:
static void Main(string[] args)
{
var innerConfigurationStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
innerConfigurationStore.CreateMap<From, To>()
.ForMember(to => to.DestinationName, opt => opt.MapFrom(from => from.Active ? from.Name : (string)null));
var innerMappingEngine = new MappingEngine(innerConfigurationStore);
Mapper.CreateMap<From, To>()
.ConvertUsing(from => from.Active ? innerMappingEngine.Map<To>(from) : null)
;
WriteMappedFrom(new From() {Active = true, Name = "ActiveFrom"});
WriteMappedFrom(new From() {Active = false, Name = "InactiveFrom"});
}
static void WriteMappedFrom(From from)
{
Console.WriteLine("Mapping from " + (from.Active ? "active" : "inactive") + " " + from.Name);
var to = Mapper.Map<To>(from);
Console.WriteLine("To -> " + (to == null ? "null" : "not null"));
}
INITIAL ANSWER
It's quite simple to use a conditional mapping in Automapper, here is some sample code
public class From
{
public bool Active { get; set; }
public string Name { get; set; }
}
public class To
{
public string DestinationName { get; set; }
}
static void Main(string[] args)
{
Mapper.CreateMap<From, To>()
.ForMember(to => to.DestinationName, opt => opt.MapFrom(from => from.Active ? from.Name : (string)null));
WriteMappedFrom(new From() {Active = true, Name = "ActiveFrom"});
WriteMappedFrom(new From() {Active = false, Name = "InactiveFrom"});
}
static void WriteMappedFrom(From from)
{
Console.WriteLine("Mapping from " + (from.Active ? "active" : "inactive") + " " + from.Name);
var to = Mapper.Map<To>(from);
Console.WriteLine("To -> " + (to.DestinationName ?? "null"));
}
There are other conditional mappings in automapper but they seem to work only on convention-based mappings. You could however look into the documentation a bit more to confirm
Upvotes: 1