为什么 automapper 在映射模型时出错?

Why automapper get error when I map model?

我在映射方面遇到了一些问题。当我尝试映射模型时出现下一个错误:

映射类型错误。

Mapping types: TeamModel -> Team Basketball.Core.Models.TeamModel -> Basketball.Core.Entities.Team

Type Map configuration: TeamModel -> Team Basketball.Core.Models.TeamModel -> Basketball.Core.Entities.Team

Destination Member: Location

我尝试映射下一个模型:

public class TeamModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public string Region { get; set; }
    public string Country { get; set; }
    public bool InPlayoff { get; set; }
    public int Wins { get; set; }
    public int Loses { get; set; }        
}

public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int LocationId { get; set; }
    public bool InPlayoff { get; set; }
    public int Wins { get; set; }
    public int Loses { get; set; }
    public Location Location { get; set; }
}

我的映射器配置:

 CreateMap<TeamModel, Team>()
   .ForMember(x => x.Id, x => x.MapFrom(y => y.Id))
   .ForMember(x => x.Name, x => x.MapFrom(y => y.Name))
   .ForMember(x => x.InPlayoff, x => x.MapFrom(y => y.InPlayoff))
   .ForMember(x => x.Wins, x => x.MapFrom(y => y.Wins))
   .ForMember(x => x.Loses, x => x.MapFrom(y => y.Loses));

我不需要映射位置、地区和国家,但如果我添加:

 .ForPath(x => x.Location.Name, x => x.MapFrom(y => y.Location))
 .ForPath(x => x.Location.Region, x => x.MapFrom(y => y.Region))
 .ForPath(x => x.Location.Country, x => x.MapFrom(y => y.Country))

Mapper 正在工作,但我说我不需要它。如何解决这个错误?我哪里弄错了?

你可以像这样忽略这个属性:

CreateMap<TeamModel, Team>()
   .ForMember(x => x.Id, x => x.MapFrom(y => y.Id))
   .ForMember(x => x.Name, x => x.MapFrom(y => y.Name))
   .ForMember(x => x.InPlayoff, x => x.MapFrom(y => y.InPlayoff))
   .ForMember(x => x.Wins, x => x.MapFrom(y => y.Wins))
   .ForMember(x => x.Loses, x => x.MapFrom(y => y.Loses))
   .ForMember(x => x.Location, opt => opt.Ignore());

忽略您不需要的自动映射器的属性。

.ForPath(x => x.Location.Name, opt => opt.Ignore())
.ForPath(x => x.Location.Region, opt => opt.Ignore())
.ForPath(x => x.Location.Country, opt => opt.Ignore())

希望对您有所帮助。