AutoMapper 覆盖源属性
AutoMapper overrides source properties
我有以下代码来更新 Student
实体:
using static AutoMapper.Mapper;
...
public void Update(StudentInputDto dto)
{
Student student = _studentRepository.GetStudent();
student = Map<Student>(dto); //student.studentnumer is null here :(
_studentRepository.Update(student);
}
我的学生实体:
public class Student
{
public Guid studentid { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
public int age { get; set; }
public Guid genderid { get; set; }
public string studentnumber { get; set; }
}
我的 StudentInputDto:
public class StudentInputDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Guid GenderId { get; set; }
}
问题是映射后Student.studentnumber为空
我想配置 AutoMapper,以便在映射后保留 Student.studentnumber。怎么做 ?任何帮助将不胜感激。
我最初的想法是按以下方式配置 AutoMapper:
Mapper.Initialize(cfg => {
cfg.CreateMap<StudentInputDto, Student>()
.ForMember(dest => dest.studentnumber, opt => opt.Ignore());
});
但是那个配置,并没有解决问题。
看看Automapper的方法描述。
TDestination Map<TDestination>(object source);
Execute a mapping from the source object to a new destination object. The source type is inferred from the source object.
student = Map<Student>(dto)
将创建一个新的 Student
对象并分配给 student
变量
要映射两个现有对象,请改用 Mapper.Map(dto, student);
TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
Execute a mapping from the source object to the existing destination
object.
我有以下代码来更新 Student
实体:
using static AutoMapper.Mapper;
...
public void Update(StudentInputDto dto)
{
Student student = _studentRepository.GetStudent();
student = Map<Student>(dto); //student.studentnumer is null here :(
_studentRepository.Update(student);
}
我的学生实体:
public class Student
{
public Guid studentid { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
public int age { get; set; }
public Guid genderid { get; set; }
public string studentnumber { get; set; }
}
我的 StudentInputDto:
public class StudentInputDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Guid GenderId { get; set; }
}
问题是映射后Student.studentnumber为空
我想配置 AutoMapper,以便在映射后保留 Student.studentnumber。怎么做 ?任何帮助将不胜感激。
我最初的想法是按以下方式配置 AutoMapper:
Mapper.Initialize(cfg => {
cfg.CreateMap<StudentInputDto, Student>()
.ForMember(dest => dest.studentnumber, opt => opt.Ignore());
});
但是那个配置,并没有解决问题。
看看Automapper的方法描述。
TDestination Map<TDestination>(object source);
Execute a mapping from the source object to a new destination object. The source type is inferred from the source object.
student = Map<Student>(dto)
将创建一个新的 Student
对象并分配给 student
变量
要映射两个现有对象,请改用 Mapper.Map(dto, student);
TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
Execute a mapping from the source object to the existing destination object.