【发布时间】:2020-02-19 14:32:38
【问题描述】:
考虑以下两个类School 和Student。学校收集了学生。学生也与未映射的学校相关联
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