gpt4 book ai didi

c# - Automapper 使用子对象覆盖列表中缺少的源属性

转载 作者:行者123 更新时间:2023-11-30 15:01:27 25 4
gpt4 key购买 nike

我对 Automapper 有疑问。我设置了一个测试 Windows 窗体应用程序,下面是代码。另请查看每个 MessageBox 之后的注释:

public class FirstClass
{
public string FirstProp { get; set; }
public IList<FirstClassChild> Children { get; set; }
}

public class FirstClassChild
{
public string FirstChildProp { get; set; }
}

public class SecondClass
{
public string FirstProp { get; set; }
public string SecondProp { get; set; }
public IList<SecondClassChild> Children { get; set; }
}

public class SecondClassChild
{
public string FirstChildProp { get; set; }
public string SecondChildProp { get; set; }
}

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

AutoMapper.Mapper.CreateMap<FirstClass, SecondClass>();
AutoMapper.Mapper.CreateMap<FirstClassChild, SecondClassChild>();

var f = new FirstClass { FirstProp = "FirstClass" };
f.Children = new List<FirstClassChild> { new FirstClassChild { FirstChildProp = "FirstClass" } };
var s = new SecondClass { FirstProp = "SecondClass", SecondProp = "SecondClass" };
s.Children = new List<SecondClassChild> { new SecondClassChild { FirstChildProp = "SecondClass", SecondChildProp = "SecondClass" } };
AutoMapper.Mapper.Map(f, s);

var fc = new FirstClassChild { FirstChildProp = "FirstClass" };
var sc = new SecondClassChild { FirstChildProp = "SecondClass", SecondChildProp = "SecondClass" };
AutoMapper.Mapper.Map(fc, sc);

MessageBox.Show(sc.FirstChildProp);//FirstClass as expected
MessageBox.Show(sc.SecondChildProp);//SecondClass as expected

MessageBox.Show(s.FirstProp);//FirstClass as expected
MessageBox.Show(s.SecondProp);//SecondClass as expected
MessageBox.Show(s.Children.First().FirstChildProp);//FirstClass as expected
MessageBox.Show(s.Children.First().SecondChildProp);//Empty not expected!!

}
}

我该怎么做才能避免这种情况?这种行为是预期的吗?无论如何,任何人都可以指导我如何使 SecondClass childs SecondChildProp 保持映射发生之前的“SecondClass”。

最佳答案

我问过类似的问题here并找到另一个类似的here .

我认为@PatrickSteele 提出了一个很好的观点:当目标列表不一定与源有任何相似之处时,AutoMapper 应该如何将源列表映射到现有对象的目标列表列表?即“But what if one list has 3 and the other list has 5?

如果您确定FirstClassSecondClass有相同数量的Children,并且如果 FirstClass 的第 N 个 child 总是对应于 SecondClass 的第 N 个 child ,您可以尝试这样的事情:

Mapper.CreateMap<FirstClass, SecondClass>()
.ForMember(m => m.Children, o => o.Ignore())
.AfterMap((src, dest) =>
{
for (var i = 0; i < dest.Children.Count; i++)
Mapper.Map(src.Children[i], dest.Children[i]);
});

或者如果 FirstChildProp 是某种唯一键:

Mapper.CreateMap<FirstClass, SecondClass>()
.ForMember(m => m.Children, o => o.Ignore())
.AfterMap((src, dest) =>
{
foreach (var dChild in dest.Children)
{
var sChild = src.Children.Single(c => c.FirstChildProp == dChild.FirstChildProp);
Mapper.Map(sChild, dChild);
}
});

关于c# - Automapper 使用子对象覆盖列表中缺少的源属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14216525/

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