这可能看起来像一个重复的问题EF Core 一对多关系列表返回 null https://stackoverflow.com/questions/55210832/ef-core-one-to-many-relationship-list-returns-null,但这个问题的答案对我没有帮助。我的情况:
public class Section
{
public int Id { get; set; }
// ...
public IEnumerable<Topic> Topics { get; set; }
}
public class Topic
{
public int Id { get; set; }
// ...
public int SectionId { get; set; }
public Section Section { get; set; }
}
但我还没有实施OnModelCreating
DbContext 中的方法,因为在这种情况下,用户身份会发生错误。数据库中存在具有指定SectionId 的主题。但无论我如何尝试获取该部分,我都会在Topics
财产。例如:
var section = _dbContext.Sections.Include(s => s.Topics).FirstOrDefault(s => s.Id == id);
出现这个问题的原因是什么?我声明有什么错误吗?或者创建主题时出现问题?
UPDATE
我试图覆盖OnModelCreating
方法如下:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Section>()
.HasMany(s => s.Topics)
.WithOne(t => t.Section);
base.OnModelCreating(modelBuilder);
}
这样:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Section>()
.HasMany(s => s.Topics)
.WithOne(t => t.Section)
.HasForeignKey(prop => prop.SectionId);
base.OnModelCreating(modelBuilder);
}
我还再次将虚拟属性添加到依赖项中。这没有帮助。添加了测试迁移(以为数据库结构可能有问题),但是迁移是空的。
SOLUTION
结果我拄着拐杖解决了这个问题:
var section = _dbContext.Sections.Include(s => s.Topics).FirstOrDefault(s => s.Id == id);
if (section == null)
{
return Error();
}
section.Topics = _dbContext.Topics.Where(t => t.SectionId == section.Id).Include(t => t.Author).ToList();
foreach(var topic in section.Topics)
{
topic.Author = _dbContext.Users.FirstOrDefault(u => u.Id == topic.AuthorId);
topic.Posts = _dbContext.Posts.Where(t => t.TopicId == topic.Id).ToList();
}
正如您所看到的,我必须显式地从 dbContext 获取数据并将它们分配给适当的属性。Include
方法调用可以被删除,因为它们不执行所需的操作。