首页 > 解决方案 > 如何在实体框架的 .Add() 中传递 DTO?

问题描述

例如

我有一个实体

学生

ID, Name, DateCreated, GUID

学生DTO

Name, DateCreated

现在自动映射器

 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

我该如何解决?

标签: c#entity-frameworkasp.net-web-apidto

解决方案


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

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

推荐阅读