ThisMember Composite object with recursive mapping

∥☆過路亽.° 提交于 2019-12-11 21:00:00

问题


I have a question, I have a following object:

public class Category {
    public long Id { get; set; }
    public string Title { get; set; }
    public int MaxDepth { get; set; }

    public virtual Category Parent { get; set; }
    public virtual IList<Category> ChildrenNodes { get; set; }
}

I'm using NHibernate to retrieve the data for this, because my list is LazyLoading, it should be remapped into CategoryDTO btw: for internal uses too.

This is how to the DTO looks like... (for the example I didn't put everything inside)

public class CategoryDTO {
    public long Id { get; set; }
    public string Title { get; set; }
    public virtual CategoryDTO Parent { get; set; }
    public IList<CategoryDTO> ChildrenNodes { get; set; }
}

I'm using ThisMember here is the reference on it.

Btw thanks Julian great tool.

I'm using it with this extension method that I wrote.

 public static TOut Map<TIn, TOut>(this TIn source)
        where TIn : class
        where TOut : new() {
        return Mapper.Map<TIn, TOut>(source);
 }

Now is the question:

How to Map a Composite object with recursion? I haven't found an answer for this within Julian examples.

Any help will be greatly appreciated.

You can suggest other mappers but it must be ThisMember speed equivalent or faster.

Thanks in advance.


回答1:


This should be fairly easy:

var catDTO = new CategoryDTO {
  Title = "Parent",
  ChildrenNodes = new List<CategoryDTO> { new CategoryDTO { Title = "Child" }}
};            

var mapper = new MemberMapper();
mapper.CreateMap<CategoryDTO, Category>(category => new Category {
  ChildrenNodes = 
    category.ChildrenNodes == null ? null :
      category.ChildrenNodes.Select(c => mapper.Map<CategoryDTO, Category>(c)).ToList()
});

var mappedCategory = mapper.Map<CategoryDTO, Category>(catDTO);


来源:https://stackoverflow.com/questions/23883387/thismember-composite-object-with-recursive-mapping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!