实体框架渴望加载不返回数据,懒惰负载 [英] Entity Framework Eager Load Not Returning Data, Lazy Load Does

查看:108
本文介绍了实体框架渴望加载不返回数据,懒惰负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用代码第一个 EF5 ,我有一个对象,它的集合定义为 virtual (懒加载)。调用时返回数据。但是我希望它能够加载。我从属性签名中删除了 virtual ,但现在它总是返回 null 数据。 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?

编辑:我知道关于 .include() 我只是喜欢使用非虚拟属性方法来执行。

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

对象

用户 [Key] Id是资源对象,个人班的父母):

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

    }
}

角色:

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).

所以如果你以任何方式关闭延迟加载 - 删除 virtual 修饰符是其中之一 - 这种行为不会变成渴望加载,而是不加载

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.

想想,假设EF将热切地加载所有没有标记为延迟加载的东西。您可以通过执行一个简单的查询来运行加载数据库的一半!

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).

这篇关于实体框架渴望加载不返回数据,懒惰负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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