我有一个简单的 ASP.NET Core (2.1) API,它使用此类的对象实现 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; }
}
我使用此实体发送 POST 请求:
var command = new Command()
{
command = "/start^cmd.exe",
clients = new List<Client>()
{
new Client()
{
nameofpc = "Zerumi"
}
}
};
// Converting to JSON and sending to api...
在 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);
}
}
postcommand方法的item参数与发送的没有什么不同。但是,如果我在保存后向/command 发送 GET 请求,我会得到这个:
[{"id":1,"command":"/start^cmd.exe","clients":null}]
为什么集合为空,我需要做什么才能更好地保存实体?
最佳答案
对我来说,似乎缺少了一些东西,但也许你在 OnModelCreating 中配置了一些东西,当我没有你的代码时很难判断。您应该在 EF 代码中使用 Pascal 大小写并将 uint 替换为 int。
然后您应该为命令和客户端添加 DTO 类(模型类)。装饰 DTO 中的每个属性,例如
[JsonProperty("command")]
为了保持正确的大小写(驼峰式大小写)。
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; }
}
关于C# ASP.NET Core 2.1/ Entity Framework : Entity collention dosen't saving,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63426104/