[英]Misunderstanding with fully defined relationship in Entity Framework Core
[英]Entity Framework Core: Include does not load relations in a fully defined relationship
给定以下三个类:
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; }
}
我想让一个 API 端点可用,它返回 Make 和相关模型。 function 如下所示:
[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);
}
这里的问题是,获取 Makes 的行不包括 Models,而是得到一个空列表。 根据微软的文档,这是一个“完全定义的关系”,应该加载具有正确外键的模型。
随着 EFC 3.0 的引入,似乎发生了一些变化,而且它似乎以前也有效。 我不知道为什么会这样。 如果有人有想法,我会很高兴。 该数据库是使用代码优先迁移创建的:版本是:
.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
数据库中充满:
我能够重现EF Core In-Memory Database Provider的问题,注释掉Make = new Make();
在Model
构造函数中解决了该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.