如何解决C#ASP.NET Core 2.1 /实体框架:实体集合不保存
我有一个简单的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参数与发送的内容相同。但是,如果在保存后将GET请求发送到/ command,我将得到此信息:
[{"id":1,"command":"/start^cmd.exe","clients":null}]
为什么colleсtion为null,并且我需要做些什么才能很好地保存实体?
解决方法
在我看来,似乎缺少了一些东西,但是也许您在OnModelCreating中配置了东西,很难分辨出我何时没有您的代码。而且,您应该在EF代码中使用Pascal-casing,并将uint替换为int。
然后,您应该为Command和Client添加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; }
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。