【问题标题】:EF 7: How to load related entities in a One-to-many relationshipEF 7:如何在一对多关系中加载相关实体
【发布时间】:2016-04-16 06:17:13
【问题描述】:

我有以下代码。 为什么我的导航属性(课程中的要求和要求中的课程)为空?

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

【问题讨论】:

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


    【解决方案1】:

    第一件事是你不需要配置你的关系两次,你只需要做一次:

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

    第二件事是,如果您正在执行查询并且希望延迟加载相关属性,恐怕这是不可能的。 EF 7 还不支持lazy loading。如您所见,有一个backlog item 跟踪延迟加载。所以,如果你需要加载一个相关的实体,你应该使用Include方法显式加载:

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

    【讨论】:

    • 谢谢你,它巧妙地解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多