Linq查询使所有调用都带来外键的表数据
from d in Customers
select d;
此查询对每个 customerId
进行调用,以获取 customerId = 该 customerId 的订单。
这使得调用又慢又长,我不需要订单数据。如何禁用它?
其他详细信息:
我正在做条件
if (flag)
{
return (from d in Customers
select d).ToList();
}
else
{
return (from d in Customers
where d.Orders.Count > 10
select d).ToList();
}
即使在 if 查询中,它也会调用每个客户的所有订单,我想在这两种情况下阻止它。
from d in Customers
select d;
This query makes a call for every customerId
to get the orders where customerId = that customerId.
This makes the call slow and long, I don't want orders data. How to disable that?
Addtional details:
I'm doing conditional
if (flag)
{
return (from d in Customers
select d).ToList();
}
else
{
return (from d in Customers
where d.Orders.Count > 10
select d).ToList();
}
Even in the if query it makes calls to all the Orders of each Customer which I want to prevent in both the cases.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如Craig Stuntz所暗示的那样,这里的问题是
客户
来自哪里以及它是什么类型。如果它是内存中的对象,则过滤全部将在内存中进行;如果它是对象查询,它将发生在您的数据库服务器上,这就是您想要的。我们无法看到足够的代码来了解有关Customers
的信息,但我会建议一个正确和错误的示例:正确(或多或少):
错误:
看出区别了吗?它是
context.Customers.ToList()
。这会运行完整的查询并将所有内容加载到内存中,然后您才有机会过滤它。在运行ToList()
之前,请确保已完全构建查询,包括where
逻辑。@Craig - 希望你不介意我接受你的想法并付诸实践。如果你有一个答案,我会投票支持你的答案。
As Craig Stuntz hinted, the question here is where
Customers
comes from and what type it is. If it's an in-memory object, the filtering is all going to happen in memory; if it's an object query, it'll happen on your database server, which is what you want. We can't see enough of your code to know much aboutCustomers
, but I'll suggest a right and wrong example:Right (more or less):
Wrong:
See the difference? It's the
context.Customers.ToList()
. That runs the full query and loads everything into memory before you have a chance to filter it. Make sure you have the query fully built, includingwhere
logic, before you runToList()
on it.@Craig - Hope you don't mind me picking up your idea and running with it. I'd have voted for your answer if you had one up.
您发布的查询不会执行此操作。访问客户实例的 Orders 属性可以做到这一点。不要访问 Orders 属性,就可以了。
如果您的代码未访问 Orders 属性,则可能某些序列化代码...为了防止该代码能够检索数据 - 处置数据上下文。要防止该代码访问 Orders 属性,请删除 dbml 中的关联。
The query you posted doesn't do that. Accessing the Orders property of a customer instance could do that. Don't access the Orders property and you'll be fine.
If your code isn't accessing the Orders property, perhaps some serialization code is... to prevent that code from being able to retrieve data - dispose the data context. To prevent that code from having an Orders property to access, remove the association in the dbml.
我转到 dataModel,并从 Customers 表中删除了 Orders 属性。现在一切正常,只需要一个电话。但我不能再做 e.Orders.Count 但我宁愿使用 join 而不是这样做来解决这个问题。
I went to the dataModel, and deleted the property Orders from Customers table. and now it works fine, there's just one call. But I can't do e.Orders.Count anymore but I would rather use join instead of doing that to solve this problem.