Reputation: 4125
I have the following code to update Student
entity:
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);
}
My student Entity:
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; }
}
My StudentInputDto:
public class StudentInputDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Guid GenderId { get; set; }
}
The problem is that Student.studentnumber is null after the mapping.
I want to configure AutoMapper in such a way that Student.studentnumber is preserved after the mapping. How to do it ? Any help would be greatly appreciated.
My initial thought was to configure AutoMapper in a following way:
Mapper.Initialize(cfg => {
cfg.CreateMap<StudentInputDto, Student>()
.ForMember(dest => dest.studentnumber, opt => opt.Ignore());
});
But that configuration, does not solve the problem.
Upvotes: 1
Views: 1806
Reputation: 2177
Take a look at method description of 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)
will create a new Student
object and assign to student
variable
To map two existing objects use Mapper.Map(dto, student);
instead
TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
Execute a mapping from the source object to the existing destination object.
Upvotes: 4