如何在实体框架的.add()中传递DTO ?



例如

我有一个实体

学生
ID, Name, DateCreated, GUID

studentsDTO

Name, DateCreated

现在automapper

CreateMap<students, studentsDTO>()
.ForSourceMember(up=> up.ID, opt=> opt.Ignore())
.ForSourceMember(up => up. GUID, opt=> opt.Ignore());
现在我有了一个方法
public IHttpActionResult AddStudents(studentsDTO model)
{
_context.Students.Add(model);
return Ok();
}

但是抛出错误,model的类型与Add的期望类型不匹配。

怎么解?

您必须在添加之前将DTO映射到您的实体,如下所示:

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

确保你已经通过控制器构造函数注入了AutoMapper:

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

然后,您可以使用AutoMapper将DTO转换为实体模型。

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

最新更新