[英]C# ASP.NET Core 2.1/Entity Framework: Entity collention dosen't saving
I have a simple ASP.NET Core (2.1) API that implements get & post methods with objects of this class:我有一个简单的 ASP.NET 核心 (2.1) API 使用此 class 的对象实现 get 和 post 方法:
public class Command
{
public uint id { get; set; }
public string command { get; set; }
public List<Client> clients { get; set; }
}
public class Client
{
public uint id { get; set; }
public string nameofpc { get; set; }
}
public class CommandContext : DbContext
{
public CommandContext(DbContextOptions<CommandContext> options) : base(options) { }
public DbSet<Command> Commands { get; set; }
}
I send POST request with this entity:我用这个实体发送 POST 请求:
var command = new Command()
{
command = "/start^cmd.exe",
clients = new List<Client>()
{
new Client()
{
nameofpc = "Zerumi"
}
}
};
// Converting to JSON and sending to api...
In CommandController.cs located this code:在 CommandController.cs 中找到以下代码:
[Route("api/[controller]")]
[ApiController]
public class CommandController : ControllerBase
{
private readonly CommandContext _context;
public CommandController(CommandContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Command>>> GetCommands()
{
return await _context.Commands.ToListAsync();
}
[HttpPost]
public async Task<ActionResult<Command>> PostCommand([FromBody] Command item)
{
_context.Commands.Add(item);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetCommand), new { item.id }, item);
}
}
The item parameter of the postcommand method is no different from what was sent. postcommand 方法的 item 参数与发送的没有什么不同。 However, if i send GET request to /command after saving, i will get this:
但是,如果我在保存后向 /command 发送 GET 请求,我会得到这个:
[{"id":1,"command":"/start^cmd.exe","clients":null}]
Why colleсtion is null and what i need to do for good entity saving?为什么集合是 null 以及我需要做些什么来保存良好的实体?
To me, it seems that something is missing, but maybe you configure stuff in OnModelCreating, hard to tell when I don't have your code.对我来说,似乎缺少了一些东西,但也许你在 OnModelCreating 中配置了东西,当我没有你的代码时很难说。 And you should use Pascal-casing in your EF-code and replace uint with int.
您应该在 EF 代码中使用 Pascal 大小写,并将 uint 替换为 int。
Then you should add DTO-classes (model-classes) for both Command and Client.然后,您应该为 Command 和 Client 添加 DTO 类(模型类)。 Decorate each property in DTO with eg
用例如装饰 DTO 中的每个属性
[JsonProperty("command")]
in order to maintain correct casing (camel-casing).为了保持正确的套管(骆驼套管)。
public class Command
{
public uint id { get; set; }
public string command { get; set; }
public List<Client> clients { get; set; }
}
public class Client
{
public int CommandId { get; set; } // foreign key
[ForeignKey(nameof(CommandId))]
public Command Command { get; set; }
public uint id { get; set; }
public string nameofpc { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.