实体框架code首先不能懒加载后保存 [英] Entity Framework Code First not lazy loading after save

查看:274
本文介绍了实体框架code首先不能懒加载后保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查找表,在我的数据库的数据表。我将利用性别和人的例子。所以我们可以说男女表看起来像这样:

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

和人表看起来像这样:

Id         Name             GenderId
1          Bob              1
2          Jane             2

我第一次像这样建模两个表中的EF code:

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;}
}

如果我在数据库中读出一个人已经那么我可以访问person.Gender。没有问题code。如果我这样做:

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;

然后,它会正确保存,但会失败在最后一行性别为空。如果我再打开一个新的上下文并加载保存的实体,那么最后一行正常工作。有没有办法,我可以直接访问后,男女的方式保存,如果我只是加载从DB?

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?

推荐答案

您的问题是,当你使用新的Person()它只是创建一个POCO对象,没有按知道如何得到它的性别属性。因此,为了使您需要的延迟加载工作<一href="http://blogs.msdn.com/b/adonet/archive/2011/02/02/using-dbcontext-in-ef-feature-ctp5-part-8-working-with-proxies.aspx">proxies.

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.

您可以创建你的人与 DbSet.Create代理( )

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

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

这篇关于实体框架code首先不能懒加载后保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆