我写了很多描述,但我认为制作一张图片会让我的问题比单词更清晰
我已将此写入地图,但它会引发异常
Mapper.CreateMap<GenericStory, GenericStoryDisplayViewModel>().ForMember(
gs => gs.StoryBody,dest => dest.MapFrom( gs => gs));
尝试将StoryWriting.Web.Models.GenericStory映射到StoryWriting.Web.ViewModels.StoryBodyViewModel。 使用StoryWriting.Web.Models.GenericStory的映射配置到StoryWriting.Web.ViewModels.GenericStoryDisplayViewModel 目的地属性:StoryBody 缺少类型映射配置或不支持的映射。 抛出了“AutoMapper.AutoMapperMappingException”类型的异常。
答案 0 :(得分:7)
我认为使用AutoMapper你也必须映射子类型,无论它们是否包含在另一个映射类型中?
所以在这种情况下你要添加
Mapper.CreateMap<GenericStory, StoryBodyViewlModel>();
然后是您当前的映射。
编辑:
我已经更新了我的测试用例,甚至可以匹配您的图像,并且它正在按预期运行:
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; }
}
然后我的测试
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();
}
结果:
答案 1 :(得分:1)
您可以使用反向映射来配置展开。看看官方的doc