gpt4 book ai didi

c# - AutoMapper: 'AutoMapper.AutoMapperMappingException' 类型的异常发生在 AutoMapper.dll 中,但未在用户代码中处理

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:53 28 4
gpt4 key购买 nike

我有类似 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);
}

但是我收到这样的错误:

An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code

源域对象和SourceViewModel类似PostPostViewModel

希望这能解释我的问题。我该如何解决这个问题?

最佳答案

根据我的经验,最有可能出现问题的是您的资源集合。

当您想使用自动映射器时,最佳做法是显式定义和注册两个实体之间的映射,此外,请确保您已经定义了实体和源子集合的 View 模型之间的映射。

关于c# - AutoMapper: 'AutoMapper.AutoMapperMappingException' 类型的异常发生在 AutoMapper.dll 中,但未在用户代码中处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30140933/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com