Search code examples
c#entity-frameworkasp.net-web-apidto

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


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?


Solution

  • 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();
     }