如何解决AutoMapper和.NET Core:配置文件无效
在ASP.NET Core应用程序中,我有一个如下的配置文件类(用于AutoMapper):
public class CandidateProfile : AutoMapper.Profile
{
public CandidateProfile()
{
CreateMap<Job.Candidate,Job.Candidate>()
.ForMember(x => x.Id,y => y.UseDestinationValue());
}
}
在Startup.cs中,我像这样用DI注册AutoMapper:
services.AddAutoMapper(c =>
{
c.AddProfile<JobProfile>();
c.AddProfile<CandidateProfile>();
c.AddProfile<ApplicationProfile>();
}
我的目标是不更改目标对象中Id属性的值。但是,目标ID始终设置为0,即源对象的值。
existingCandidate = _mapper.Map(app.Candidate,existingCandidate);
调用此代码后,现有的Candidate.Id为0。
我在做什么错了?
解决方法
我的目标是不更改Id属性的值。 目标对象。
因此,基本上对于Id
,您不希望将源属性映射到目标属性。您希望它独自离开。只需Ignore
然后对该属性进行映射-
CreateMap<Candidate,Candidate>()
.ForMember(x => x.Id,y => y.Ignore());
编辑:
以下是适用于上述配置(版本10.0)的代码-
public void Test()
{
Candidate appCandidate = new Candidate { Id = 0,Name = "alice" };
Candidate existingCandidate = new Candidate { Id = 4,Name = "bob" };
existingCandidate = _Mapper.Map(appCandidate,existingCandidate);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。