0

我想使用 Entity Framework 4.2 建立一个对象图。

现在,我有 POCO 实体,使用 ICollection 作为导航属性。我想避免使用 EntityCollection 或任何特定于 EF 的东西。

我想避免过度使用 Include 引起的大量连接。给定一个对象,我想填充它的导航属性,从而产生一个单独的数据库查询。

有没有办法直接填充 ICollection?现在,我正在解决这个问题,但这真的很痛苦。

// grab the user, brand users and brands
User user = entities.Users
                    .Include(item => item.BrandUsers.Select(brandUser => brandUser.Brand))
                    .Where(item => item.Name == userName)
                    .SingleOrDefault();
// grab the pending share grants and brands
entities.Users
        .Include(item => item.ToShareGrants.Select(shareGrant => shareGrant.Brand))
        .Where(item => item.Id == user.Id)
        .Load();
return user;

我不喜欢这种方法的一件事是我正在重新查询顶级对象。如果我不这样做,则在没有返回任何对象时不会填充导航属性(左为 NULL)。例如,以下代码在返回结果时才有效:

entities.ShareGrants
        .Include(item => item.Brand)
        .Where(item => item.ToUserId == user.Id)
        .Load();

我很好奇在实体框架中是否有一种我不知道的方法来建立这些类型的关系。如果有人知道分步填写导航属性的简单方法,我将不胜感激代码示例。

4

3 回答 3

0

尝试关闭当前查询的延迟加载,您可以将其放在 using 块中

entities.ContextOptions.LazyLoadingEnabled = false;
于 2012-01-26T22:39:43.363 回答
0

你的问题不是很清楚。为什么不在Include同一个查询中使用多个 s

User user = entities.Users
      .Include(item => item.BrandUsers.Select(brandUser => brandUser.Brand))
      .Include(item => item.ToShareGrants.Select(shareGrant => shareGrant.Brand))
      .Where(item => item.Name == userName)
      .SingleOrDefault();
于 2012-01-27T00:27:20.550 回答
0

这个问题的简短回答是 EF4 没有直接支持我想要的功能。为了防止大规模连接并在对数据库的多次调用中分解结果,必须再次从数据库中下载最顶层的实体。这意味着结果集中最左边的列将是为每条记录重复的实体的列。

于 2012-07-31T23:55:48.533 回答