Reputation: 2363
I have a simple ASP.NET Core (2.1) API that implements get & post methods with objects of this class:
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:
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:
[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. However, if i send GET request to /command after saving, i will get this:
[{"id":1,"command":"/start^cmd.exe","clients":null}]
Why colleсtion is null and what i need to do for good entity saving?
Upvotes: 2
Views: 85
Reputation: 10794
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. And you should use Pascal-casing in your EF-code and replace uint with int.
Then you should add DTO-classes (model-classes) for both Command and Client. Decorate each property in DTO with e.g.
[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; }
}
Upvotes: 4