I'm new to the .NET Core framework. When I trying with Entity Framework Core, I couldn't get the relational object of entity.
This is my sample code:
public class TodoItemT
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
public virtual List<SubItemT> SubItems { get; set; }
}
public class SubItemT
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[ForeignKey("TodoItemT")]
public long TodoId { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
public virtual TodoItemT TodoItemT { get; set; }
}
public class TodoContext : Microsoft.EntityFrameworkCore.DbContext
{
public TodoContext(DbContextOptions<TodoContext> options) : base(options)
{
}
public DbSet<TodoItemT> TodoItemTs { get; set; }
public DbSet<SubItemT> SubItemTs { get; set; }
}
And I have this in Startup.cs:
services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
After I insert data to the database.
I try to get data from database with controller
// GET: api/Todo
[HttpGet]
public async Task<ActionResult<IEnumerable<TodoItemT>>> GetTodoItemTs()
{
return await _context.TodoItemTs.ToListAsync();
}
But what I got is
[
{
"id": 1,
"name": "string",
"isComplete": true,
"subItems": null
}
]
I expected to get this instead:
[
{
"id": 1,
"name": "task 1",
"isComplete": true,
"subItems": [
{
"id": 1,
"name": "sub 1",
"isComplete": true,
}
]
}
]
Did I do something wrong or having wrong configuration?
Thank you for the help.
Include. You can only get what you want by projecting to DTOs, otherwisesubItemswill always contain the back referenceTodoItemT, which is not in the JSON you want. Using the entity classes themselves would cause reference loops in the JSON serializer. Also,Includedoesn't work with in-memory database, which you shouldn't use for testing anyway. EF themselves advise against it.