Entity Framework Code First not lazy loading after save

倾然丶 夕夏残阳落幕 提交于 2019-12-10 14:19:07

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/11027657/entity-framework-code-first-not-lazy-loading-after-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!