要从多个级别加载数据,请使用include,然后在将项目更新到dotnet core 3.1之后,它将无法工作,并且第四级始终为null
var oldMethod = _depositRepository.All()
.Include(n => n.StudentStatus.Student.Person.Gender)
我尝试使用ThenInclude
var newMethod = _depositRepository.All()
.Include(n => n.StudentStatus)
.ThenInclude(s => s.Student)
.ThenInclude(p => p.Person)
.ThenInclude(g => g.Gender)
在这两种方法中,Gender
总是null
public IQueryable<T> All()
{
return DbSet.AsNoTracking().AsQueryable();
}
我遵循本教程加载相关数据
编辑1:我的一些代码
public class IEntity<IId>
{
public IId Id { get; set; }
public string Name { get; set; }
}
public class Gender : IEntity<byte>
{
}
public class Person: IEntity<int>
{
public byte GenderId { get; set; }
public virtual Gender Gender { get; set; }
}
public class Student : IEntity<int>
{
public int PersonId { get; set; }
public virtual Person Person { get; set; }
}
public class StudentStatus : IEntity<int>
{
public int StudentId { get; set; }
public virtual Student Student { get; set; }
}
public class Deposit : IEntity<int>
{
public int StudentStatusId { get; set; }
public StudentStatus StudentStatus { get; set; }
}
public interface IRepository<T, IId>
where T : IEntity<IId>
{
IQueryable<T> All();
}
public class EfRepository<T, IId> : IRepository<T, IId>
where T : IEntity<IId>
{
private readonly UniversityDbContext _dbContext;
public EfRepository(UniversityDbContext dbContext)
{
_dbContext = dbContext;
}
private DbSet<T> DbSet => _dbContext.Set<T>();
public IQueryable<T> All()
{
return DbSet.AsNoTracking().AsQueryable();
}
public class FinancialController : Controller
{
private readonly IRepository<Deposit, int> _depositRepository;
public FinancialController(IRepository<Deposit, int>)
{
_depositRepository = depositRepository;
}
public IActionResult GetStatistic()
{
var model= _depositRepository.All()
.Include(n => n.StudentStatus)
.ThenInclude(s => s.Student)
.ThenInclude(p => p.Person)
.ThenInclude(g => g.Gender).ToList();
return Json(model);
}
}
我得出的结论是,您可以使用的深度ThenInclude
有三个级别的限制。因此,我通过调用_genderRepository
并传递GenderId
以获取Gender
对象来解决该问题,但是我认为这不是最好的解决方案,但是比编写sql
代码更容易。
var newMethod = _depositRepository.All()
.Include(n => n.StudentStatus)
.ThenInclude(s => s.Student)
.ThenInclude(p => p.Person)
.ThenInclude(g => g.Gender)
.Select(n=>new {
...
Gender=_genderRepository.Find(k=>k.Id==n.StudentStatus.Student.Person.GenderId)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句