Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First not lazy loading after save

I have a lookup table and a data table in my db. I'll use gender and person for an example. So let's say the gender table looks like so:

Id         Code
1          Male
2          Female

and the person table looks like so:

Id         Name             GenderId
1          Bob              1
2          Jane             2

I've modelled both tables in EF code first like so:

public class Gender
{
    public int Id {get;set;}
    public string Code {get;set;}
}

public class Person
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int GenderId {get;set;}

    public virtual Gender {get;set;}
}

If I read a person already in the DB then I can access person.Gender.Code without a problem. If I do this:

var person = new Person
             {
                 Name = "Bob",
                 GenderId = 1,
             };

context.People.Add(person);
context.SaveChanges();

var code = person.Gender.Code;

Then it will save correctly but will fail on the last line as gender is null. If I then open a new context and load the saved entity then the last line works fine. Is there a way that I can access gender directly after a save as if I just loaded the entity from the DB?

like image 367
VARAK Avatar asked Jun 14 '12 06:06

VARAK


People also ask

How do I enable lazy loading code first in Entity Framework?

Lazy loading means delaying the loading of related data, until you specifically request for it. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.

How do I stop lazy loading in Entity Framework?

We can disable lazy loading for a particular entity or a context. To turn off lazy loading for a particular property, do not make it virtual. To turn off lazy loading for all entities in the context, set its configuration property to false.

Does EF core lazy load by default?

The advice is not to use lazy loading unless you are certain that it is the better solution. This is why (unlike in previous versions of EF) lazy loading is not enabled by default in Entity Framework Core.

Does Entity Framework support lazy loading?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.


1 Answers

Your problem is that when you use new Person() it will just create a POCO object which doesn't know how to get the it's Gender property. So to make the lazy loading work you need proxies.

You can create your person as a proxy with DbSet.Create():

var person = context.People.Create();
person.Name = "Bob";
person.GenderId = 1;

context.People.Add(person);
context.SaveChanges();
like image 134
nemesv Avatar answered Nov 14 '22 21:11

nemesv