LazyLoading 不适用于我的实体
这是我的班级
public class Pergunta
{
[Key]
public int Id { get; set; }
public string Descricao { get; set; }
public string Alias { get; set; }
public int CategoriaId { get; set; }
public virtual Categoria Categoria { get; set; }
}
和“类别”类
public class Categoria
{
[Key]
public int Id { get; set; }
public string Descricao { get; set; }
}
但是当我调用端点时:
public async Task<IActionResult> Index()
{
List<Pergunta> teste = await _context.Pergunta.ToListAsync();
return _context.Pergunta != null ?
View(await _context.Pergunta.ToListAsync()) :
Problem("Entity set 'SistemaJustificativasContext.Pergunta' is null.");
}
var“teste”表示“Categoria”为空:
为什么延迟加载不起作用?我是不是忘记了什么?
我认为你应该使用 .Include 方法。 https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.entityframeworkqueryableextensions.include?view=efcore-7.0
类似 _context.Pergunta.Include(x => x.Categoria)
试试这个
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseLazyLoadingProxies() .UseSqlServer(myConnectionString);
查看更多详细信息https://learn.microsoft.com/en-us/ef/core/querying/lated-data/lazy如@scotty13建议。