.net core AutoMapper和.NET Core:配置文件无效

.net core AutoMapper和.NET Core:配置文件无效,.net-core,automapper,.net Core,Automapper,在ASP.NET核心应用程序中,我有一个配置文件类(用于AutoMapper),如下所示: public class CandidateProfile : AutoMapper.Profile { public CandidateProfile() { CreateMap<Job.Candidate, Job.Candidate>() .ForMember(x => x.Id, y => y.UseDestinat

在ASP.NET核心应用程序中,我有一个配置文件类(用于AutoMapper),如下所示:

 public class CandidateProfile : AutoMapper.Profile
{
    public CandidateProfile()
    {
        CreateMap<Job.Candidate, Job.Candidate>()
            .ForMember(x => x.Id, y => y.UseDestinationValue());
    }
}
 services.AddAutoMapper(c =>
        {
            c.AddProfile<JobProfile>();
            c.AddProfile<CandidateProfile>();
            c.AddProfile<ApplicationProfile>();
        }
调用此代码后,existingCandidate.Id为0

我做错了什么

我的目标是不更改 目标对象

因此,对于
Id
,基本上不希望源属性映射到目标属性。你想让它一个人呆着。只需
忽略该属性的映射即可-

CreateMap()
.ForMember(x=>x.Id,y=>y.Ignore());
编辑:
以下是使用上述配置(版本10.0)为我工作的代码-

公共无效测试()
{
候选者appCandidate=新候选者{Id=0,Name=“alice”};
候选者existingCandidate=新候选者{Id=4,Name=“bob”};
existingCandidate=_Mapper.Map(appCandidate,existingCandidate);
}

我也尝试了.Ignore(),但同样的情况也发生了。Id的值被覆盖(设置为0)我在console应用程序中尝试了您的场景,但效果不好,我看到automapper在映射时初始化了目标类型。所以我找到了一个解决办法,可能不是很好的解决办法,但可以解决你的问题。使用
mapper.Map(source,opt=>opt.BeforeMap((src,dest)=>{src.id=destination.id;}))
existingCandidate = _mapper.Map(app.Candidate, existingCandidate);