gpt4 book ai didi

c# - Linq、模拟联接和 Include 方法

转载 作者:行者123 更新时间:2023-11-30 21:23:14 25 4
gpt4 key购买 nike

我正在调查一个与...相关的问题 Join and Include in Entity Framework

基本上,以下查询返回当前用户有权 (ACL) 查看的“属性”对象列表。

IQueryable<Property> currPropList 
= from p in ve.Property
.Include("phyAddress")
.Include("Contact")
from a in ve.ACLs
from u in ve.Account
from gj in ve.ObjectGroupJoin
where u.username == currUsername // The username
&& (a.Account.id == u.id // The ACLs
&& a.objType == (int)ObjectType.Group)
&& (gj.ObjectGroup.id == a.objId // The groups
&& gj.objId == p.id) // The properties
select p;

查询返回正确的属性列表并且在大范围内工作正常。

但是上面的 linq 查询中的“Include”调用不会加载对象。如果我在 LINQ 查询之后显式调用“Load()”,则会加载对象。

related SO question建议“Include”调用和 where 子句之间可能存在冲突。怎么会这样呢?

但无论如何,我如何重组这个查询以加载“phyAddress”和“Contract”成员?具体来说,我只想加载返回对象的成员,而不是数据库中的所有“phyAddress”和“Contact”对象。

谢谢。

编辑

我已经追踪到使用多个 from 子句的问题

这有效...

IQueryable<Property> currPropList 
= from p in ve.Property
.Include("phyAddress")
select p;

并且加载了“phyAddress”成员。

但这行不通...

IQueryable<Property> currPropList 
= from p in ve.Property
.Include("phyAddress")
from a in ve.ACLs
select p;

基本上,当有多个 from 子句时,Include 调用将被忽略。有谁知道解决这个问题的办法吗?

编辑2

一种解决方法是将 IQueryable 结果转换为 ObjectQuery 并从中获取包含。但我想阻止我假设这是导致数据库的第二次往返。

例如。这行得通....

IQueryable<Property> currPropList 
= ((from p in ve.Property
from a in ve.ACLs
select p) as ObjectQuery<Property>).Include("phyAddress");

有没有办法只用一个查询就可以做到这一点?

编辑3

由于延迟执行,没有第二个查询[ http://blogs.msdn.com/charlie/archive/2007/12/09/deferred-execution.aspx .所以编辑 2 将是解决方案。

最佳答案

这是 Include 的一个已知问题...如果您执行某些更改查询形状的操作(即从 from),则 Include 会丢失,但有足够简单的解决方法:

  1. 您可以将包含包含在查询周围,参见 Tip 22 - How to make include really include .
  2. 或者您可以在 select 子句中获得所需的一切,让关系修复为您完成这项工作。即

    var x = from p in ve.Property  
    from a in ve.ACLs
    select new {p,p.phyAddress};

    var results = x.AsEnumerable().Select(p => p.p);

现在结果是属性实体的枚举,但每个实体都加载了 phyAddress,这是对 phyAddress 的初始请求和 EF 的关系修复的副作用。

关于c# - Linq、模拟联接和 Include 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1894555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com