gpt4 book ai didi

c# - EF 7 : How to load related entities in a One-to-many relationship

转载 作者:太空狗 更新时间:2023-10-30 00:18:33 28 4
gpt4 key购买 nike

我有以下代码。为什么我的导航属性(Requirement in Course 和 Courses in Requirement)为空?

    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 不支持 lazy loading然而。如您所见,有一个 backlog item跟踪延迟加载。因此,如果您需要加载相关实体,您应该使用 Include 方法显式加载:

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

关于c# - EF 7 : How to load related entities in a One-to-many relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34730005/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com