automapper class and nested class map to one class

Deadly 提交于 2019-12-01 18:30:50
Khepri

I thought with AutoMapper you had to map sub-types as well, regardless of if they were contained in another mapped type?

So in this case you'd add

Mapper.CreateMap<GenericStory, StoryBodyViewlModel>();

and then your current mapping.

EDIT:

I've updated my test case to even match your images and it's functioning as expected:

public class GenericStory
{
    public string Description { get; set; }
    public int Id { get; set; }
    public bool IsFavoritedByCurrentUser { get; set; }
    public int StoryTypeId { get; set; }
    public string StoryTypeName { get; set; }
    public string Html { get; set; }
    public string Title { get; set; }
    public int TotalFavoritedByUsers { get; set; }
}

public class GenericStoryDisplayViewModel
{
    public string Description { get; set; }
    public int Id { get; set; }
    public int StoryTypeId { get; set; }
    public string StoryTypeName { get; set; }

    public StoryBodyViewModel StoryBody { get; set; }
}

public class StoryBodyViewModel
{
    public string Title { get; set; }
    public string Html { get; set; }

    public int TotalFavoritedByUsers { get; set; }
    public bool IsFavoritedByCurrentUser { get; set; }
}

and then my test

private static void Main()
{
    var story = new GenericStory
    {
        Description = "Lorem ipsum dolor sit amet,....etc",
        Html = "<h1>ZOMG!</hl>\r\n\r\n<h2>BEES!</h2>",
        Id = 9,
        IsFavoritedByCurrentUser = true,
        StoryTypeId = 1,
        StoryTypeName = "ShortStory",
        Title = "Test Story",
        TotalFavoritedByUsers = 1
    };

    var vm = new GenericStoryDisplayViewModel();

    Mapper.CreateMap<GenericStory, StoryBodyViewModel>();
    Mapper.CreateMap<GenericStory, GenericStoryDisplayViewModel>()
       .ForMember(dest => dest.StoryBody, opt => opt.MapFrom(src => src));

    Mapper.Map(story, vm);

    Console.ReadKey();
}

Results:

You can use reverse mapping for configure unflattening. Look at the official doc

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