gpt4 book ai didi

mapping - 使用 Automapper 忽略具有默认值的映射属性

转载 作者:行者123 更新时间:2023-12-02 15:17:19 25 4
gpt4 key购买 nike

我使用 Automapper 将对象映射到对象目标。有什么方法可以仅将具有非默认值的属性从对象映射到目标对象吗?

最佳答案

关键点是仅在满足这些条件时才检查源属性的类型和映射(对于引用类型,!= null;对于值,!= default类型):

Mapper.CreateMap<Src, Dest>()
.ForAllMembers(opt => opt.Condition(
context => (context.SourceType.IsClass && !context.IsSourceValueNull)
|| ( context.SourceType.IsValueType
&& !context.SourceValue.Equals(Activator.CreateInstance(context.SourceType))
)));

完整的解决方案是:

public class Src
{
public int V1 { get; set; }
public int V2 { get; set; }
public CustomClass R1 { get; set; }
public CustomClass R2 { get; set; }
}

public class Dest
{
public int V1 { get; set; }
public int V2 { get; set; }
public CustomClass R1 { get; set; }
public CustomClass R2 { get; set; }
}

public class CustomClass
{
public CustomClass(string id) { Id = id; }

public string Id { get; set; }
}

[Test]
public void IgnorePropertiesWithDefaultValue_Test()
{
Mapper.CreateMap<Src, Dest>()
.ForAllMembers(opt => opt.Condition(
context => (context.SourceType.IsClass && !context.IsSourceValueNull)
|| ( context.SourceType.IsValueType
&& !context.SourceValue.Equals(Activator.CreateInstance(context.SourceType))
)));

var src = new Src();
src.V2 = 42;
src.R2 = new CustomClass("src obj");

var dest = new Dest();
dest.V1 = 1;
dest.R1 = new CustomClass("dest obj");

Mapper.Map(src, dest);

//not mapped because of null/default value in src
Assert.AreEqual(1, dest.V1);
Assert.AreEqual("dest obj", dest.R1.Id);

//mapped
Assert.AreEqual(42, dest.V2);
Assert.AreEqual("src obj", dest.R2.Id);
}

关于mapping - 使用 Automapper 忽略具有默认值的映射属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37194731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com