我遇到类似this.的问题,但是此答案对我不起作用。
我正在做一个小项目。我有两个域模型(Post,Source):
public class Post
{
public Post()
{
Sources = new HashSet<Source>();
}
public int Id { get; set; }
public string Title { get; set; }
public string About { get; set; }
public bool IsPublished { get; set; }
public bool IsFinished { get; set; }
public DateTime? CreatedOn { get; set; }
public int? CreatedBy { get; set; }
public virtual ICollection<Source> Sources { get; set; }
}
public class PostViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string About { get; set; }
public bool IsPublished { get; set; }
public bool IsFinished { get; set; }
public DateTime? CreatedOn { get; set; }
public int? CreatedBy { get; set; }
public virtual ICollection<SourceViewModel> Sources { get; set; }
}
public ActionResult Edit(int id)
{
Mapper.CreateMap<Post, PostViewModel>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Title))
.ForMember(dest => dest.About, opt => opt.MapFrom(src => src.About))
.ForMember(dest => dest.IsPublished, opt => opt.MapFrom(src => src.IsPublished))
.ForMember(dest => dest.IsFinished, opt => opt.MapFrom(src => src.IsFinished))
.ForMember(dest => dest.CreatedOn, opt => opt.MapFrom(src => src.CreatedOn))
.ForMember(dest => dest.CreatedBy, opt => opt.MapFrom(src => src.CreatedBy))
.ForMember(dest => dest.Sources, opt => opt.MapFrom(src => src.Sources))
.ReverseMap();
var Post = _PostService.Get(id);
var model = Mapper.Map<Post, PostViewModel>(Post);
return View(model);
}
但是我收到这样的错误:
AutoMapper.dll中发生类型为'AutoMapper.AutoMapperMappingException'的异常,但未在用户代码中处理
源域对象与
SourceViewModel
类似,Post
和PostViewModel
。希望这可以解释我的问题。我该如何解决这个问题?
最佳答案
以我的经验,最可能的问题是您的资源集中。
当您要使用自动映射器时,最佳实践是显式定义和注册两个实体之间的映射。此外,请确保已定义实体与源子集合的视图模型之间的映射。
关于c# - AutoMapper:AutoMapper.dll中发生了类型为'AutoMapper.AutoMapperMappingException'的异常,但未在用户代码中处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30140933/