AutoMapper:如何在 C# 中使用 AutoMapper 从映射中忽略子对象的子项

帕博达

我有以下类结构

    public class Parent
    {
        public int ParentID { get; set; }
        public string ParentName { get; set; }
        public Child Child { get; set; }
    }

    public class ParentMap
    {
        public int ParentID { get; set; }
        public string ParentName { get; set; }
        public Child Child { get; set; }
    }

    public class Child
    {
        public int ChildID { get; set; }
        public string ChildName { get; set; }
        public InnerChild InnerChild { get; set; }
    }

    public class InnerChild
    {
        public int InnerChildID { get; set; }
        public string InnerChildName { get; set; }
        public Parent Parent { get; set; }
    }

我想ParentParentMap班级映射班级。映射后,我需要ParentChild对象。但我不需要ParentChild.InnerChild对象(可以将其设置为null)。我已经尝试ForPath()过如下。但它会停止映射整个Child对象。

CreateMap<Parent, ParentMap>()
  .ForPath(o => o.Child.InnerChild, opt => opt.Ignore());

有人可以告诉我如何解决这个问题。

红葱头

这是解决您的问题的一种快速方法

CreateMap<Parent, ParentMap>()
    .AfterMap((src, dst) =>
    {
        dst.Child.InnerChild = null;
    });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章