我有以下代码:
[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; }
}
int?
如果值为null
unless ,它基本上allowOverride = true
会水合一个值,其中它将在不检查字段值的情况下水合该值。
我将如何在 Automapper 中执行此操作?
我知道您可以使用 .Condition() ,如下所示:
但我不知道如何:
- 应用基于的逻辑,
int?
无需一一定义。 allowOverride
将布尔值包含到 Mapper。