【问题标题】:Get child along with parent让孩子和父母一起
【发布时间】:2020-02-19 14:32:38
【问题描述】:

考虑以下两个类SchoolStudent。学校收集了学生。学生也与未映射的学校相关联

public class School
{
    public int Id { get; set; }
    public virtual ICollection<Student> students { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public int SchoolId { get; set; }
    public string Name { get; set; }
    public bool Deleted { get; set; }
    public virtual School School { get; set; }
}

我的模型构建器看起来像这样

modelBuilder.Entity<School>()
        .HasMany(obj => obj.students)
        .WithOne()
        .HasForeignKey(obj => obj.SchoolId)
        .OnDelete(DeleteBehavior.Cascade)
        .IsRequired();

modelBuilder.Entity<Student>(entity =>
{
    entity.HasOne(e => e.School);
});

什么有效 -

var result = mydbcontext.Schools
                        .Include(d => d.students)
                        .Where(d => d.Id == 1)
                        .Select(x => new School
                        {
                            Id = x.Id,
                            students = x.students.Where(s => !s.Deleted).ToList()
                        })
                        .AsNoTracking()
                        .ToList();

什么不工作 -

var school = mydbcontext.Students
                        .Include(x => x.School) //returning null
                        .Where(s => !s.Deleted)
                        .ToList();

当我尝试上面的代码时,我得到了所有没有被删除的学生,但是我得到了 Empty 学校的结果

我这里有什么遗漏吗?

【问题讨论】:

  • 我认为删除 [NotMapped] 会起作用
  • 感谢@PankajRawat,但没有运气

标签: c# entity-framework linq .net-core


【解决方案1】:

这看起来很可能是由 StudentSchool 属性上的 [NotMapped] 属性引起的。使用该属性指示 EF 不要在数据库中创建对应的列来将 Student 记录键入回 School 记录,因此 EF 将无法推断 Student->Schoolrelationship,只有School->Students 关系。

【讨论】:

  • 请注意,删除该属性可能需要您运行dotnet ef database update,并且您可能需要重新填充测试数据。
  • 感谢您的建议。但没有运气。删除NotMapped,添加迁移并更新数据库
  • @KrishnaMuppalla 您能否查询数据库中的Students 表并确认它现在正在使用School 记录的有效外键填充School 列?此外,查看您的模型构建器的 fluent API,您可能希望在学校的.WithOne() 中添加学生-学校关系,如下所示:.WithOne(s =&gt; s.School)
  • 添加WithOne(s=&gt;s.School后,它开始工作了。不幸的是,我得到了过滤的学生->学校->学校内的所有学生。我可以将此限制为仅加载学校而不加载所有学生吗?
  • 听起来您指的是相关实体的延迟加载 (docs.microsoft.com/en-us/ef/ef6/querying/…)。您应该能够通过从 Student 类的 School 属性声明中删除 virtual 来防止这种情况发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多