C# Include()不在查询中加载关系。它们仅在collection.load()或另一个表的无关查询中填写
调用我的端点时,我没有填充C# Include()不在查询中加载关系。它们仅在collection.load()或另一个表的无关查询中填写,c#,.net,asp.net-core,entity-framework-core,core,C#,.net,Asp.net Core,Entity Framework Core,Core,调用我的端点时,我没有填充student.StudentPublished。仅当在AContext.StudentPublished上调用查询或使用Collection.Load()时,我才能获得为关系填充的任何数据。为什么不使用实体框架创建此联接 设置上下文: public partial class AContext : DbContext { public AContext(DbContextOptions<AContext> options): base(option
student.StudentPublished
。仅当在AContext.StudentPublished
上调用查询或使用Collection.Load()
时,我才能获得为关系填充的任何数据。为什么不使用实体框架创建此联接
设置上下文:
public partial class AContext : DbContext
{
public AContext(DbContextOptions<AContext> options): base(options) { }
public virtual DbSet<Student> Students { get; set; }
public virtual DbSet<StudentPublished> StudentPublished { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new StudentConfiguration());
modelBuilder.ApplyConfiguration(new StudentPublishedConfiguration());
base.OnModelCreating(modelBuilder);
}
}
终点:
public IActionResult Get(int id)
{
var student = dataContext.Students.Include(s=>s.StudentPublished).FirstOrDefault(s=>s.ReferenceNumber == id);
return Ok(student);
}
尝试将控制器中的方法更改为:
public IActionResult Get(int id)
{
var student = dataContext.Students
.Where(s => s.ReferenceNumber == id)
.Include(s => s.StudentPublished)
.FirstOrDefault();
return Ok(student);
}
因此,在我的头重重地敲击键盘之后,我尝试使用nuget
Microsoft.EntityFrameworkCore.Proxies
并在启动时启用上下文配置中的延迟加载。我不知道为什么这会让include
以正确的方式快速加载,但它确实有效 StudentPublished表或数据库对象的主键是什么?另外,您是否可以尝试修改您的学生类以包含一个构造函数作为public Student(){StudentPublished=new List();}@sam,我用另一个配置更新了问题并尝试了构造函数,但构造函数只给出了一个空列表,而不是端点中的null。
public partial class Student
{
public int ReferenceNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<StudentPublished> StudentPublished { get; set; }
}
public partial class StudentPublished
{
public int ReferenceNumber { get; set; }
public bool Ok { get; set; }
public Student Student { get; set; }
}
public IActionResult Get(int id)
{
var student = dataContext.Students.Include(s=>s.StudentPublished).FirstOrDefault(s=>s.ReferenceNumber == id);
return Ok(student);
}
public IActionResult Get(int id)
{
var student = dataContext.Students
.Where(s => s.ReferenceNumber == id)
.Include(s => s.StudentPublished)
.FirstOrDefault();
return Ok(student);
}