如何存储从LINQ查询到DB的中间结果,避免客户端评估或运行部分查询几次



有一个LINQ查询:

var firstOrDeFault = context.ADbSet
.Where(a => a.Id == uniqueId) //1 record matching, I want to store it somewhere
.SelectMany(a => a.b) 
.Where(b=> b.c.Select(x => x.ListProperty.Id).Contains(otherUniqueId)) //1 record matching, I want to store it somewhere
.FirstOrDefault(); //this is stored in the variable I assign to

问题是我想收集我在注释中指出的中间结果,但是这样做我想避免:

  • 客户端对这些中间结果的查询的评估
  • 遍历记录几次,因为我存储了中间结果(天真地我可以单独运行部分查询,但这是浪费时间)

这样做不会导致客户端执行。

尝试以下查询。我希望唯一id真的是唯一的。

var query = 
from a in context.ADbSet
where a.Id == uniqueId
from b in a.b
from c in b.c
where c.ListProperty.Id == otherUniqueId
select new 
{
a,
c
};
var first = query.First();
var a = first.a;
var c = first.c;

最新更新