I have the following code:
[Test]
public void ConditionalMapping()
{
var src = new Sample1 {Age = 1, Number = null};
var dest = new Sample2 {Age = null, Number = 1};
Hydrate(src, dest, false);
Assert.That(dest.Age, Is.EqualTo(1));
Assert.That(dest.Number, Is.EqualTo(1));
src = new Sample1 {Age = null, Number = 1};
dest = new Sample2 {Age = 1, Number = null};
Hydrate(src, dest, true);
Assert.That(dest.Age, Is.Null);
Assert.That(dest.Number, Is.EqualTo(1));
}
public void Hydrate(Sample1 src, Sample2 dest, bool allowOverride)
{
if (!dest.Age.HasValue || allowOverride)
dest.Age = src.Age;
if (!dest.Number.HasValue || allowOverride)
dest.Number = src.Number;
}
public class Sample1
{
public int? Age { get; set; }
public int? Number { get; set; }
}
public class Sample2
{
public int? Age { get; set; }
public int? Number { get; set; }
}
Which basically hydrates an int?
if the value is null
unless allowOverride = true
, in which it will hydrate the value without checking the value of the field.
How would I go about doing this in Automapper?
I know that you can use .Condition() as shown here:
Automapper's condition gets ignored
But I couldn't figure out how to:
- Apply the logic based on
int?
without defining it one by one. - Include the
allowOverride
boolean to the Mapper.