Christopher Francisco
Christopher Francisco

Reputation: 16258

EF Code First lazy loading doesnt work

Consider the following entities:

public class MyEntity1 {
    public int ID {get; set;}

    public int MyEntity2ID {get; set;}
    public virtual MyEntity2 {get; set;}
}

public class MyEntity2{
    public int ID {get; set;}

    public virtual ICollection<MyEntity1> MyEntity1s{get; set;}
}

Inside the controller's create method for MyEntity1 I go like this

// Create POST
UnitOfWork.MyEntity1Repository.Insert(myEntity1); // It contains a value for MyEntity2ID already
UnitOfWork.Save();

// Also tried this but still doesn't work:
// myEntity1 = UnitOfWork.MyEntity1Repository.GetById(myEntity1.ID);

myEntity1.MyEntity2.SomeProperty;  // MyEntity2 return nulls.

Why is this happening? is lazy loading only supposed to work when called on the razor view or something?

Upvotes: 0

Views: 210

Answers (2)

Aron
Aron

Reputation: 15772

You are mistaking a POCO for a Entity Framework Proxy, they are not the same thing. The fact that EF requires the keyword virtual on properties to allow Lazy Loading should give you a clue on how EF does Lazy Loading.

Try new up a DbContext get a MyEntity1 out and do .GetType() see what the ACTUAL type is.

So...now we have established that EF does NOT use your MyEntity1 class, and created its own class which subclasses MyEntity1, how do we get a "new" of this subclass. The answer is to do DbContext.MyEntity1s.Create();.

Upvotes: 1

Shan Plourde
Shan Plourde

Reputation: 8706

Try declaring MyEntity2.MyEntity1s as virtual and make sure your table has appropriate fks defined.

Upvotes: 0

Related Questions