I have a database I created using entity code first
In that DB I have a structure similar to the following
class ClassA
{
public virtual int ID {get;set}
public virtual string some_text {get;set}
public virtual ClassB B {get;set}
public virtual ClassC C {get;set}
...
}
class ClassB
{
public virtual int ID {get;set}
public virtual string some_text {get;set}
public virtual string some_values {get;set}
...
}
class ClassC
{
public virtual int ID {get;set}
public virtual string some_text {get;set}
public virtual string some_values {get;set}
...
}
....
Finally I have a context for those objects with all of the interface to query the DB
public class ClassADb : DBContext, IClassADataSource
{
public DBSet<ClassA> As {get;set}
public DBSet<ClassB> Bs {get;set}
public DBSet<ClassC> Cs {get;set}
...
}
When I create the DB and explore it I can see that it was created what seems to be correctly:
In the ClassA_Table I see foreign keys for ClassB_ID, ClassC_ID, etc as well as all of the primitive types encapsulated in ClassA (ints, strings, bools, dates, etc)
Also when performing something along the lines of:
ClassB MyB = new ClassB();
//some code to initialize B
...
Bs.Add(MyB)
ClassC MyC = new ClassC();
//some code to initialize C
Cs.Add(MyC);
ClassA MyA = new ClassA();
A.B = MyB;
A.C = MyC;
...
db.SaveChanges();
I again explore the DB and see in Table_A a new row with references to those B and C objects (row id’s corresponding to those objects in the B_table , C_table)
The Problem I am having is that when I do a select from As container , I can retrieve the A object but the nested B and C objects are null
The primitive types are OK (not empty)
Some fixes I tried
The virtual keyword is lazy , so in the constructor of the class accessing the database i did
db.Configuration.ProxyCreationEnabled = false;
But still when doing something along the lines of
A myA = db.As.Find(1);
A.some_text ; // not null
A.B ; //NULL!!!!
A.C ; // NULL
What is causing the entity framework not to fetch the A and B object?
You have to explicitly load related entities explicitly using
Include().In newer version of the Entity Framework there is also a wrapper method around this method accepting a lambda expression avoiding the strings.