Lazy loading is not working on my entity.
Here is my class:
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; }
}
And this is the class Categoria
:
public class Categoria
{
[Key]
public int Id { get; set; }
public string Descricao { get; set; }
}
But when I call this endpoint:
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.");
}
The var teste
says that Categoria
is null:
Why is the lazy loading not working? Did I forget something?
Try this
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseLazyLoadingProxies() .UseSqlServer(myConnectionString);
see more details out there https://learn.microsoft.com/en-us/ef/core/querying/related-data/lazy as @scotty13 suggested.