Entity Framework中调用.Add()方法时如何正确传入DTO类型参数?
错误原因
你当前EF上下文的_context.Students是DbSet<students>类型,只能接收students类的实体对象,而你传入的是studentsDTO类型的参数,二者类型不匹配因此触发报错。核心问题是你缺少了DTO转实体类的映射转换步骤,同时原有AutoMapper配置仅配置了实体转DTO的单向映射,没有覆盖DTO转实体的反向映射规则。
解决方案
- 第一步:调整AutoMapper映射配置,新增DTO转实体的映射规则,如果你的ID、GUID不需要手动赋值(比如ID是数据库自增主键、GUID是插入时自动生成),可以直接配置双向映射:
// 原有实体转DTO的配置保留 CreateMap<students, studentsDTO>() .ForSourceMember(up=> up.ID, opt=> opt.Ignore()) .ForSourceMember(up => up.GUID, opt=> opt.Ignore()); // 新增DTO转实体的映射配置,忽略不需要手动赋值的字段 CreateMap<studentsDTO, students>() .ForMember(dest => dest.ID, opt => opt.Ignore()) .ForMember(dest => dest.GUID, opt => opt.Ignore());
如果映射规则简单,也可以用ReverseMap()简化双向配置:
CreateMap<students, studentsDTO>() .ForSourceMember(up=> up.ID, opt=> opt.Ignore()) .ForSourceMember(up => up.GUID, opt=> opt.Ignore()) .ReverseMap() // 自动生成反向映射规则 .ForMember(dest => dest.ID, opt => opt.Ignore()) .ForMember(dest => dest.GUID, opt => opt.Ignore());
- 第二步:修改接口方法,先将入参的DTO映射为实体对象,再执行插入操作,同时补充数据库提交逻辑:
public IHttpActionResult AddStudents(studentsDTO model) { // 将DTO转换为students实体对象 var studentEntity = _mapper.Map<students>(model); _context.Students.Add(studentEntity); // 必须调用SaveChanges才会将数据持久化到数据库 _context.SaveChanges(); // 可按需返回生成的主键等信息给前端 return Ok(studentEntity.ID); }
注意:如果使用依赖注入获取AutoMapper的
IMapper实例,需要提前在服务注册逻辑中完成AutoMapper的配置注入,确保映射规则能正常加载。
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

