Home > Net >  How do I pass a DTO in .Add() of entity framework?
How do I pass a DTO in .Add() of entity framework?

Time:09-24

For example

I have an entity

students

ID, Name, DateCreated, GUID

studentsDTO

Name, DateCreated

now automapper

 CreateMap<students, studentsDTO>()
                .ForSourceMember(up=> up.ID, opt=> opt.Ignore())
                .ForSourceMember(up => up. GUID, opt=> opt.Ignore());

now I have a method

public IHttpActionResult AddStudents(studentsDTO model)
        {
            _context.Students.Add(model);
            return Ok();
        }

but throws error that type of model doesn't match the expected type in Add.

How do I solve it?

CodePudding user response:

You have to map your DTO to your entity before adding, like this:

public IHttpActionResult AddStudents(studentsDTO model)
{
    _context.Students.Add(_mapper.Map<Students>(model));
    return Ok();
}

CodePudding user response:

Make sure you have the AutoMapper injected via the controller constructor:

private readonly IMapper _mapper;

public StudentsController(IMapper mapper)
{
    _mapper = mapper;
}

Then, you can use the AutoMapper to convert the DTO to the entity model.

public IHttpActionResult AddStudents(studentsDTO model)
{
       students students = _mapper.Map<Students>(model);
       _context.Students.Add(students);

       return Ok();
 }
  • Related