EF 7:如何以一对多关系加载相关实体 [英] EF 7: How to load related entities in a One-to-many relationship
问题描述
我有以下代码. 为什么我的导航属性(课程中的需求"和课程中的需求")为空?
I have the following code. Why are my navigation properties (Requirement in Course, and Courses in Requirement) are null?
public class Course : AbsEntity {
[Key]
public string Title { get; set; }
public string Term { get; set; }
public int Year { get; set; }
public string CourseId { get; set; }
public double GradePercent { get; set; }
public string GradeLetter { get; set; }
public string Status { get; set; }
public int ReqId { get; set; }
public Requirement Requirement { get; set; }
}
public class Requirement : AbsEntity {
[Key]
public int ReqId { get; set; }
public string ReqName { get; set; }
public ICollection<Course> Courses { get; set; }
}
// In DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().HasOne(c => c.Requirement).WithMany(r => r.Courses).HasForeignKey(c => c.ReqId);
modelBuilder.Entity<Requirement>().HasMany(r => r.Courses).WithOne(c => c.Requirement);
}
推荐答案
第一件事是您不需要配置两次关系,只需要做一次:
First thing is you don't need to configure your relationship twice, you just need to do it one time:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().HasOne(c => c.Requirement)
.WithMany(r => r.Courses)
.HasForeignKey(c => c.ReqId);
}
第二件事是,如果您正在执行查询,并且希望延迟加载相关属性,那么恐怕将不可能. EF 7目前还不支持延迟加载.如您所见,有一个积压项目跟踪延迟加载.因此,如果需要加载相关实体,则应使用Include
方法显式加载:
Second thing is if you are doing a query and you are expecting to lazy load the related properties, I'm afraid is not going to be possible. EF 7 doesn't support lazy loading yet. As you can see there is a backlog item tracking Lazy Loading. So, if you need to load a related entity, you should use explicit loading using Include
method:
var query= ctx.Courses.Include(c=>c.Requirement).Where(...)...;
这篇关于EF 7:如何以一对多关系加载相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!