实体框架 - 预先加载相关实体 [英] Entity Framework - Eager loading related entities

查看:148
本文介绍了实体框架 - 预先加载相关实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架4 MVC和需要确保任何引用的实体我想在我看来,使用控制器方法返回之前已加载,否则认为吐出来的是可怕的:

I'm using Entity Framework 4 with MVC and need to ensure any referenced entities I want to use in my view have been loaded before the controller method returns, otherwise the view spits out the dreaded:

的ObjectContext的实例已被释放,并可以不再被用于需要连接的操作。

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

在从上下文中选择直,我就可以使用包含(字符串)要包括在生成的SQL查询方法,迫使他们:

When selecting straight from the context, I can just use the Include(string) method to force them to be included in the generated SQL query:

var sellers = context.Sellers.Include("Recommendations.User").ToList();

不过,如果我有(例如)接受一个实体,需要加载的所有项目一个辅助方法,也没有包含方法可用。

void Test(Seller seller)
{
    // ensure all recommendations and their users are loaded
}

的蛮力的方法是遍历他们:

The brute force approach is to loop through them:

foreach (var recommendation in seller.Recommendations)
    recommendation.User.ToString(); // just force a load

如果我有100个建议,这将创造背后的幕后101 SQL查询。理想的情况是我想的方法/方法,加载所有建议用户只有单趟SQL对象。

If I have 100 recommendations, this will create 101 SQL queries behind-the-scenes. Ideally I want a method/approach that loads all Recommendation AND User objects with only a single trip to SQL.

给我钱。

修改我不是在讨论这是否是一个好的或坏的建筑很感兴趣。我已经简化我的方案为客户着想的问题。你可以做什么,我要问的EF API?

EDIT I'm not really interested in discussing whether this is a good or bad architecture. I've simplified my scenario for the sake of the question. Can you do what I'm asking with the EF API?

编辑2

<一个href="http://stackoverflow.com/questions/3671193/entity-framework-eager-loading-related-entities/3671354#3671354">Ladislav's编辑提供了一种新的方法的希望,但似乎我不太有。

Ladislav's edit offered hope of a new approach, but it seems I'm not quite there.

我可以实现我通过这样想:

I can achieve what I want via this:

context.Sellers.Include("Recommendations.User").Single(s => s.Id == seller.Id);

这个方法不会使用正常工作 LoadProperty ...

This approach doesn't work using LoadProperty...

context.LoadProperty(seller, "Recommendations.User");

......,因为它失败,出现错误...

...as it fails with the error...

指定的导航属性Recommendations.User找不到。

The specified navigation property Recommendations.User could not be found.

如果你没有提及的上下文无论这些方法的工作

Neither of these approaches work if you don't have a reference to the context.

推荐答案

这是一个老问题,但在EF6可以完成像的这个

This is an old question, but in EF6 you can accomplish loading dependent objects on an entity like this:

context.Entry(seller).Collection(s => s.Recommendations).Query().Include(r => r.User)).Load();

这将加载所有建议及相关用户对于给定的卖家

That would load all Recommendations and their related Users for the given seller

这篇关于实体框架 - 预先加载相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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