EF 7:如何以一對多關係加載相關實體

asp.net asp.net-core c# entity-framework entity-framework-core

我有以下代碼。為什麼我的導航屬性(課程要求和要求課程)為空?

    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);
            }

一般承認的答案

首先,您不需要兩次配置您的關係,您只需要執行一次:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Course>().HasOne(c => c.Requirement)
                                .WithMany(r => r.Courses)
                                .HasForeignKey(c => c.ReqId);          
}

第二件事是如果你正在進行查詢並且你期望延遲加載相關屬性,我恐怕是不可能的。 EF 7還不支持延遲加載 。如您所見,有一個積壓項目跟踪延遲加載。因此,如果需要加載相關實體,則應使用Include方法使用顯式加載:

 var query= ctx.Courses.Include(c=>c.Requirement).Where(...)...;


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow