Given the following three classes:
public class Make
{
public int MakeId { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public ICollection<Model> Models { get; set; }
public Make()
{
Models = new Collection<Model>();
Name = string.Empty;
}
}
public class Model
{
public int ModelId { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public Make Make { get; set; }
public int MakeId { get; set; }
Model()
{
Name = string.Empty;
Make = new Make();
}
}
public class VegaDbContext : DbContext
{
public VegaDbContext(DbContextOptions<VegaDbContext> options) : base(options)
{
}
public DbSet<Make> Makes { get; set; }
public DbSet<Model> Models { get; set; }
}
I want to make an API endpoint available that returns Make and related Models. The function for that looks like the following:
[HttpGet("/api/makes")]
public async Task<IEnumerable<MakeResource>> GetMakes()
{
// Here Models is not being loaded!
var makes = await dbContext.Makes.Include(m => m.Models).ToListAsync();
// This is manually loading the required data, which works. But I don't want to do this.
foreach (var make in makes)
{
make.Models = await dbContext.Models.Where(m => m.MakeId == make.MakeId).ToListAsync();
}
// This mapper part is not of interest
return mapper.Map<IList<Make>, IList<MakeResource>>(makes);
}
The problem here is, that the line fetching the Makes does not include the Models, instead I get an empty list. According to Microsoft's documentation, this is a "fully defined relationship" and the models with the correct foreign keys should be loaded.
It seems there have been some changes with the introduction of EFC 3.0 and it seems to have worked before. I have no idea why this is the case. If anyone has an idea, I'd be glad! The database was created using code first migrations. The versions are:
.NET Core SDK (reflecting any global.json):
Version: 3.1.103
Commit: 6f74c4a1dd
Runtime Environment:
OS Name: manjaro
OS Version:
OS Platform: Linux
RID: arch-x64
Base Path: /usr/share/dotnet/sdk/3.1.103/
Host (useful for support):
Version: 3.1.3
Commit: ed88943d24
.NET Core SDKs installed:
3.1.103 [/usr/share/dotnet/sdk]
.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.1.3 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.3 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download
The database is filled with: