本文介绍了实体框架贪婪加载不返回数据,延迟加载是否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用code首先 EF5 我也有定义为集合虚拟对象(延迟加载)。调用时这将返回的数据。不过,我希望它是渴望加载。我已经删除虚拟从属性的签名,但现在它总是返回数据。 EF甚至不运行查询后,任何人都可以帮忙吗?

编辑:我知道 .INCLUDE()我只是preFER用做它的非虚拟财产法

对象

用户 [重点] Id为资源对象,它是人类的父上):

 命名空间实体
{
    [表(用户)]
    公共类用户:人
    {    [需要]
    公众的ICollection<的角色和GT;角色{搞定;组; }    }
}

角色:

 命名空间实体
{
    公共类角色
    {
        [键]
        公共字符串ID {搞定;组; }        公共虚拟的ICollection<使用者>用户{搞定;组; }
    }
}


解决方案

这是一种常见的混乱。懒加载相反的是:没有的加载的除非的你明确地做加载自己(通过预先加载,例如使用包含 )。

所以,如果你关闭以任何方式延迟加载 - 删除虚拟修改就是其中之一 - 的行为不变成预先加载没有加载

想想看,假设EF会急切地加载未标记为延迟加载的一切。您运行通过做一件简单的查询加载一半的数据库的风险!

有方式来作出缺席导航属性渴望加载(如果你还是会希望,阅读后以上)。

I'm using code first EF5 and I have an object which has a collection defined as virtual (lazy loaded). This returns data when called. However I want it to be eager loaded. I've removed virtual from the property signature but now it always returns null data. EF doesn't even run the query, can anyone help?

Edit: I know about .include() I'd just prefer to use the non-virtual property method of doing it.

Objects

User ([Key] Id is on Resource object which is the Parent of person class):

namespace Entities
{
    [Table("Users")]
    public class User : Person
    {

    [Required]
    public ICollection<Role> Roles { get; set; } 

    }
}

Role:

namespace Entities
{
    public class Role
    {
        [Key]
        public string Id { get; set; }

        public virtual ICollection<User> Users { get; set; } 
    }
}
解决方案

This is a common confusion. The opposite of lazy loading is: no loading unless you explicitly do the loading yourself (e.g. by eager loading using Include).

So if you turn off lazy loading in any way — removing the virtual modifier is one of them — the behaviour does not turn into eager loading but no loading.

Think of it, suppose EF would eagerly load everything that is not marked for lazy loading. You run the risk of loading half the database by doing one simple query!

There is no way to make a navigation property eager loading by default (if you'd still want that after reading the above).

这篇关于实体框架贪婪加载不返回数据,延迟加载是否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:29