C# ASP.NET Core 2.1/ Entity Framework : Entity collention dosen't saving

标签 c# entity-framework asp.net-core

我有一个简单的 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/

相关文章:

c# - 匿名方法的丑陋之处和优点-C#

entity-framework - Entity Framework - 错误 11007 : Entity type is not mapped.

c# - 如何从谓词中调用 TryParse

c# - 从 .Net 调用 native 函数时参数值困惑

c# - 如何在 MVVM 应用程序中将任意 View 动态插入 xaml?

.net - Enum 支持 Entity Framework 数据库优先

mysql - 将实体添加到 Symfony2 表单时使用多个属性

asp.net-core - NPoco 在 .net Core 中的使用

c# - 引用循环处理忽略不适用于 Asp.Net Core 3.0 Preview 3

c# - 如何在 asp.net Core Razor Pages 中填充复选框列表?