简体   繁体   English

实体框架代码首先不保存后延迟加载

[英]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: 而person表看起来像这样:

Id         Name             GenderId
1          Bob              1
2          Jane             2

I've modelled both tables in EF code first like so: 我首先在EF代码中为这两个表建模,如下所示:

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. 如果我读了一个已经在数据库中的人,那么我可以访问person.Gender.Code没有问题。 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? 是否有一种方法可以在保存后直接访问性别,就好像我刚从数据库中加载实体一样?

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. 你的问题是,当你使用new Person()它只会创建一个POCO对象,它不知道如何获取它的Gender属性。 So to make the lazy loading work you need proxies . 因此,要使延迟加载工作,您需要代理

You can create your person as a proxy with DbSet.Create() : 您可以使用DbSet.Create()将您的人员创建为代理:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM