使用 Automapper C# 映射模型时出错

问题描述 投票:0回答:1

由于某种原因,映射无法正常工作。我设置了映射配置以从 TopicModel 获取 Id (Guid) 并将其映射到 Topic 的 UId (Guid),但它仍然尝试将 Id (Guid) 映射到 Id (int)。

此处出现错误:

    private class PostTopicsResolver : IValueResolver<CreatePostModel, Post, ICollection<Topic>>
    {
        public ICollection<Topic> Resolve(CreatePostModel source, Post destination, ICollection<Topic> member, ResolutionContext context)
        {
            return context.Mapper.Map<ICollection<Topic>>(source.Topics);
        }
    }

这是我尝试绘制地图的方式:

public class TopicModel
{
    public required Guid Id { get; set; }
}

public class TopicModelProfile : Profile
{
    public TopicModelProfile()
    {
        CreateMap<TopicModel, Topic>()
            .ForMember(dest => dest.Uid, opt =>
                opt.MapFrom(src => src.Id));

        CreateMap<Topic, TopicModel>()
            .ForMember(dest => dest.Id, opt =>
                opt.MapFrom(src => src.Uid));
    }
}

我尝试绘制双向地图。我尝试将 TopicModel 的映射配置放入 CreatePostModel 中,但没有任何帮助。

班级:

public class Topic : BaseEntity
{
  public required string Type { get; set; }
  public virtual ICollection<User> Users { get; set; }
  public virtual ICollection<Post> Posts { get; set; }
}

[Index("Uid", IsUnique = true)]
public abstract class BaseEntity
{
  [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public virtual int Id { get; set; }
  [Required]
  public virtual Guid Uid { get; set; } = Guid.NewGuid();
}
c# asp.net .net automapper
1个回答
0
投票

我为不应该映射的 id 属性添加了显式的忽略配置,这解决了问题。感谢“菲尔多”

© www.soinside.com 2019 - 2024. All rights reserved.