asp.net-mvc-3 - 正在延迟加载为 null 的急切加载的相关对象

标签 asp.net-mvc-3 entity-framework poco eager-loading

我正在急切加载(通过使用 .Include())相关实体,以便最大限度地减少为特别“庞大”的数据网格生成的 SQL 查询的数量。在 POCO 中,相关实体是公共(public)虚拟导航属性,这意味着它们是延迟加载的。我想保留延迟加载这些相关实体的默认行为,因为它最适合我项目的其他部分。

现在,在预加载相关实体之后,我可以看到仍然生成了相当数量的查询。这是仅针对相关实体的查询为空(空只是因为 sql 连接“发现”没有相关数据)。

这让我相信,当我稍后在表示层中访问它们时,EF 会尝试延迟加载这些实体(认为它们尚未加载)。

我是不是漏掉了一些基本的东西,或者有什么方法可以解决这个问题?

示例代码
使用存储库模式,这里有一些简化的方法(省略分页、排序、过滤等)。

通用存储库中的获取方法

public IEnumerable<T> Get(
    Expression<Func<T, object>>[] includes = null)
{
    IQueryable<T> query = set;

    ...

    // Include properies for eager loading
    if (includes != null)
    {
       query = includes.Aggregate(query, 
          (current, include) => current.Include(include));
    }

    ...

    return query.ToList();
}

上面是从服务类调用的,像这样

...
context.Licenses.Get(
    includes: new Expression<Func<License, object>>[] { l => l.Comment }
);
...

许可 POCO

public class License
{
    public License()
    {
    }

    // Primitive properties
    public string ID { get; set; }
    public string Name { get; set; }
    ...
    // Navigation properties
    public virtual LicenseComment Comment { get; set; }
    ...
}

LicenseComment POCO

public class LicenseComment
{
    public LicenseComment()
    {
    }

    // Primitive properties
    public string LicenseID { get; set; }
    public string Comment { get; set; }
}

访问 MVC Razor View 中的属性(或为此目的在模型中)

<span>@license.Comment</span>


每当我尝试访问一个空的 License.Comment(通过 SQL Server Profiler 查找它)时,都会生成额外的 SQL 查询,在我看来, Entity Framework 延迟加载开始了,尽管我急切地包含了这个属性。

最佳答案

我无法尝试,但我希望这不会发生。无论如何,如果您有一个不想延迟加载的页面,您可以简单地关闭该页面:

context.Configuration.LazyLoadingEnabled = false;

或者您可以关闭这些查询的代理创建 - 未代理的实体不能使用延迟加载:

context.Configuration.ProxyCreationEnabled = false;

关于asp.net-mvc-3 - 正在延迟加载为 null 的急切加载的相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11673251/

相关文章:

c# - 通过 boundfield 将 DBCONTEXT 绑定(bind)到 gridview

c++ - 错误: field 'dateOfBirth' has incomplete type 'Poco::Data::Date'

c# - POCO 1.5.1 Websocket 客户端无法连接到 c# websocket 服务器

asp.net-mvc - MVC Ajax 与 Ajax.ActionLink

c# - 如何以与 stackoverflow 相同的方式路由 URL

forms - ASP MVC 3 RAZOR动态表单生成贴

c# - 无法访问已处置的对象。交易

c# - SQL Server 将 SP_EXECUTESQL 识别为对象而不是过程名称

C# 将 System.Data.Entity.DynamicProxies 克隆到实际(非代理)类?

jquery - 如何设计页面右侧的文本框mvc razor