1
votes

Given the following 3 (simplified) classes:

  • ClassA { int Id; }
  • ClassB { int Id; }
  • JunctionClass { ClassA classA; ClassB classB; }

When I am trying to load the JunctionClass list...

var junctionClassList = _appDbContext.JunctionClass
                                     .Include(jc => jc.ClassA)
                                     .Include(jc => jc.ClassB).ToList();

the code doesn't load the ClassA and ClassB objects.

I have found a fix, but I don't think that I'm using EF Core the way it should be used:

var classAList = _appDbContext.ClassA.ToList();
var classBList = _appDbContext.ClassB.ToList();

var junctionClassList = _appDbContext.JunctionClass
                                     .Include(jc => jc.ClassA)
                                     .Include(jc => jc.ClassB).ToList();

This way, the junctionClassList object will also load the classA and classB dependencies.

My question is this - is this the correct way to use lazy/eager loading? Or is there another way?

2
did you add virtual keyword for ClassA and ClassB in JunctionClass? - Ercan Peker
I did, but still no results. However, I did not update the database after adding the "virtual" keyword. Should I? - Next Gen Me
Which EF Core version u have ? - vivek nuna
2.1.3-rtm-32065 - Next Gen Me

2 Answers

0
votes

You are using Eager loading in this case using Include. Lazy loading is introduced in EF Core 2.1. You need to enable it explicitly.

-1
votes

Below defination works for Include.

    public class JunctionClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ClassA ClassA { get; set; }
    public virtual ClassB ClassB { get; set; }

}
public class ClassA
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class ClassB
{
    public int Id { get; set; }
    public string Name { get; set; }

}

Share us the difference from yours.