[英]Manipulating entity framework to eliminate round trips to the database
Let's say I have the following bit of code (which I know could be easily modified to perform better, but it illustrates what I want to do) 假设我有以下一些代码(我知道可以很容易地修改它以便更好地执行,但它说明了我想要做的事情)
List<Query> l = new List<Query>;
// Query is a class that doesn't exist, it represents an EF operation
foreach (var x in Xs)
{
Query o = { context.someEntity.Where(s=>s.Id==x.Id).First();}
// It wouldn't execute it, this is pseudo code for delegate/anonymous function
l.Add(o)
}
Then send this list of Query to EF, and have it optimize so that it does the least amount of round trips possible. 然后将此查询列表发送给EF,并对其进行优化,以便尽可能减少往返次数。 Let's call it BatchOptimizeAndRun;
我们称之为BatchOptimizeAndRun; you would say
你会说
var results = BatchOptimizeAndRun(l);
And knowing what it knows from the schema it would reduce the overall query to an optimal version and execute that and place the read results in an array. 并且知道它从模式中知道什么,它会将整个查询减少到最佳版本并执行该查询并将读取结果放入数组中。
I hope I've described what I'm looking for accurately and more importantly that it exists. 我希望我已经准确地描述了我正在寻找的东西,更重要的是它已经存在。 And if I sound like a rambling mad man, let's pretend this question never existed.
如果我听起来像一个漫无边际的疯子,让我们假装这个问题从未存在过。
I'd have to echo Mr. Moore's advice, as I too have spent far too long constructing a linq-to-entities query of monolithic proportions only to find that I could have made a stored procedure in less time that was easier to read and faster to execute. 我不得不回应摩尔先生的建议,因为我也花了太长时间构建一个整体比例的linq-to-entities查询,却发现我可以在更短的时间内完成一个更容易阅读的存储过程。更快执行。 That being said in your example...
在你的例子中说...
List<int> ids = Xs.Select(x => x.Id).ToList();
var results = context.someEntity.Where(s => ids.Contains(s.Id)).ToList();
I believe this will compile to something like 我相信这会编译成类似的东西
SELECT
*
FROM
someEntity
WHERE
Id IN (ids) --Where ids is a comma separated list of INT
Which will provide you with what you need. 这将为您提供所需的一切。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.