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

时间:2013-01-08 13:57:58

标签: c# automapper

我遇到了Automapper的问题。我设置了一个测试窗体应用程序,下面是代码。另请查看每个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孩子SecondChildProp保持“SecondClass”,就像映射发生前一样。

1 个答案:

答案 0 :(得分:5)

我问了一个类似的问题here,发现了另一个类似问题here

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

如果,您确定FirstClassSecondClass具有相同数量的Children如果 {{1第N个孩子总是对应FirstClass的第N个孩子,你可以尝试这样的事情:

SecondClass

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