c# - 我不断收到错误消息,即我的 .NET 模型需要具有 0 args 或仅可选 args 的构造函数?
问题描述
我正在阅读 .NET REST API 教程,该教程通过 sql server 后端为 .NET 中的命令行命令执行 CRUD。我正在使用邮递员向我的端点发送请求,如果我向我的端点发送一个发布请求,它只带有一个包含 CommandCreateDTO 的所有请求的对象,它会出现此错误: System.ArgumentException: Commander.Models.Command needs to have a constructor with 0 args or only optional args. (Parameter 'type')
. 想法?
控制器
//POST api/commands
[HttpPost]
public ActionResult<CommandCreateDto> CreateCommand(CommandCreateDto commandCreateDto)
{
var commandModel = _mapper.Map<Command>(commandCreateDto);
_repository.CreateCommand(commandModel);
_repository.SaveChanges();
return Ok(commandModel);
}
CommandReadDto
namespace Commander.Dtos
{
public class CommandReadDto
{
public int Id { get; set; }
public string HowTo { get; set; }
public string Line { get; set; }
public CommandReadDto(int Id, string HowTo, string Line)
{
this.Id = Id;
this.HowTo = HowTo;
this.Line = Line;
}
}
}
命令创建Dto
namespace Commander.Dtos
{
public class CommandCreateDto
{
public string HowTo { get; set; }
public string Line { get; set; }
public string Platform { get; set; }
public CommandCreateDto(string HowTo, string Line, string Platform)
{
this.HowTo = HowTo;
this.Line = Line;
this.Platform = Platform;
}
}
}
命令模型
using System.ComponentModel.DataAnnotations;
namespace Commander.Models
{
public class Command
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(250)]
public string HowTo { get; set; }
[Required]
public string Line { get; set; }
[Required]
public string Platform { get; set; }
public Command(int Id, string HowTo, string Line, string Platform)
{
this.Id = Id;
this.HowTo = HowTo;
this.Line = Line;
this.Platform = Platform;
}
}
}
命令配置文件
using AutoMapper;
using Commander.Dtos;
using Commander.Models;
namespace Commander.Profiles
{
public class CommandsProfile : Profile
{
public CommandsProfile()
{
//Source - Target
CreateMap<Command, CommandReadDto>();
CreateMap<CommandCreateDto, Command>();
}
}
}
解决方案
Your Automapper CreateMap()
is trying to map Command class with CommandReadDto
. To do that it is expecting default constructor(Constructor without any parameter) in your Command
model.
To solve your problem add new default constructor to your Command.Model
class.
using System.ComponentModel.DataAnnotations;
namespace Commander.Models
{
public class Command
{
...
public Command(){} //This is missing in your code.
public Command(int Id, string HowTo, string Line, string Platform)
{
this.Id = Id;
this.HowTo = HowTo;
this.Line = Line;
this.Platform = Platform;
}
}
}
推荐阅读
- sql - PostgreSQL - 如果所有列值都是“A”或 NULL,我如何返回 id
- docker - 无法使用 Google Kubernetes Engien Nginx 入口控制器获得 HTTP 基本身份验证
- javascript - 写动画
- c++ - 编译类模板时出现很多错误
- android - 亚行不断崩溃
- docker - Docker 应该在创建容器时触发公共休息调用
- node.js - 从 Google Cloud Storage 读取文件流到 ffmpeg(使用 fluent-ffmpeg)
- java - ThreadpoolExecutor ,当其中一个正在运行的线程抛出异常时,正在等待其他正在运行的线程完成
- python - 比术语聚合更有效的聚合?
- amazon-web-services - 跟踪 AWS 对象/服务