I'm unable to return the child data from the second table linked buy a Foreign key with the first table.
I have the following Tables that has been created using Entity Framework Core Code first approach :
public class BoardGame
{
public int id { get; set; }
public double price { get; set; }
public List<BoardGameTitle> BoardGameTitle{get;set;}
}
public class BoardGameTitle
{
public int id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int languageId { get; set; }
public int BoardGameId{get;set;}
public BoardGame BoardGame{get;set;}
}
public class TableFlipDB :DbContext{
public TableFlipDB (DbContextOptions<TableFlipDB> options)
:base(options)
{}
public DbSet<BoardGame> BoardGame{get;set;}
public DbSet<BoardGameTitle> BoardGameTitle{get;set;}
protected override void OnModelCreating(ModelBuilder modelBuilder){
modelBuilder.Entity<BoardGame>().HasMany(bg=>bg.BoardGameTitle).WithOne(bg=>bg.BoardGame);
//modelBuilder.Entity<BoardGameTitle>().HasOne(BoardGameTitle=>BoardGameTitle.BoardGame).WithMany(BoardGameTitle=>BoardGameTitle.BoardGameTitle);
}
}
the second table BoardGameTitle
contains a Foreign key to the following table BoardGame
through the property BoardGameId
,
When ever I retrieve the list of board games I cant get the related data from the second table in the property BoardGameTitle
the property returns null
my Controller
public ActionResult<List<BoardGame>> GetAll()
{
return TableFlipDB.BoardGame.ToList();
}
Expected Result was:
[
{
"id": 1,
"price": 100,
"boardGameTitle": [
{
"id": 1,
"name": "b1",
"description": "b1",
"languageId": 1,
"boardGameId": 1,
"boardGame": {
"id": 1,
"price": 100,
"boardGameTitle": []
}
}
]
},
{
"id": 2,
"price": 200,
"boardGameTitle": [
{
"id": 2,
"name": "b2",
"description": "b2",
"languageId": 1,
"boardGameId": 2,
"boardGame": {
"id": 2,
"price": 200,
"boardGameTitle": [
{
"id": 3,
"name": "b22",
"description": "b22",
"languageId": 2,
"boardGameId": 2
}
]
}
},
{
"id": 3,
"name": "b22",
"description": "b22",
"languageId": 2,
"boardGameId": 2,
"boardGame": {
"id": 2,
"price": 200,
"boardGameTitle": [
{
"id": 2,
"name": "b2",
"description": "b2",
"languageId": 1,
"boardGameId": 2
}
]
}
}
]
}
]
But the Result I got
[
{
"id": 1,
"price": 100,
"boardGameTitle": null
},
{
"id": 2,
"price": 200,
"boardGameTitle": null
}
]
I have found the solution as @Elyas Esna in the comments section said I need to change the controller return statement from return TableFlipDB.BoardGame.ToList();
to return TableFlipDB.BoardGame.Include(p=>p.BoardGameTitle).ToList();