EF4慢关联访问
我正在使用 EF4 构建 ASP.NET 4 Web 应用程序,并且有如下表:
产品
属性产品属性映射
Product_Attribute_Map 是一个多对多的交叉表。因此产品可以有零个或多个属性,反之亦然。
在代码中我这样做:
//Attribute a = new Attribute(); // Edit:
Attribute a = (from a in context.Attributes where a.AttributeID = 1 select a).First();
a.Name = "test";
Product.Attributes.Add(a);
我注意到一个问题导致速度非常慢。 EF4 将在服务器上执行此 SQL:
SELECT
[Extent2].* FROM [dbo].[Product_Attribute_Map] AS [Extent1]
INNER JOIN [dbo].[Product] AS [Extent2] ON [Extent1].[ProductID] = [Extent2].[ProductID]
WHERE [Extent1].[AttributeID] = @p1
我不明白它为什么这样做。一个属性可能会分配给 10.000 个产品,这使得这是一个错误的查询。向产品添加属性需要超过 5 秒的时间...
如何防止 EF4 选择所有属性?只需选择该产品的属性即可。
谢谢
编辑:这仅使用 POCO t4 模板。 EntityObject 模板不存在这个问题。
I'm building an ASP.NET 4 web application using EF4 and I have tables like this:
Product
AttributeProduct_Attribute_Map
Product_Attribute_Map is a cross table, many to many. So Product can have zero or many Attribute and vice versa.
In code I do this:
//Attribute a = new Attribute(); // Edit:
Attribute a = (from a in context.Attributes where a.AttributeID = 1 select a).First();
a.Name = "test";
Product.Attributes.Add(a);
I noticed a problem which makes this very slow. EF4 will execute this SQL on the server:
SELECT
[Extent2].* FROM [dbo].[Product_Attribute_Map] AS [Extent1]
INNER JOIN [dbo].[Product] AS [Extent2] ON [Extent1].[ProductID] = [Extent2].[ProductID]
WHERE [Extent1].[AttributeID] = @p1
I don't understand why it does this. An Attribute may be assigned to 10.000 Products, which makes this a bad query. It takes over 5 seconds to add an Attribute to a Product...
How can I prevent EF4 from selecting all attributes? And just select the attributes for this product.
Thanks
Edit: This is only using POCO t4 template. EntityObject template doesnt have this problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测:发生这种情况是因为 LazyLoading 与 POCO 模板生成的 FixUpCollections 一起使用。当您向产品添加属性时,修复集合也会执行反向操作 - 它将向属性添加产品,但首先访问属性中的产品集合将触发延迟加载,因此您的查询将被执行。我不喜欢修复集合...您可以修改 POCO 模板以不使用它们,或者可以删除“属性”中的“产品”导航属性(如果不需要)。
My guess: This happens because of LazyLoading used together with FixUpCollections generated by POCO template. When you add attribute to product, fixup collection will perform reverse operation as well - it will add prduct to attribute but first access to products collection in attribute will trigger lazy loading and so your query is executed. I don't like fixup collections ... You can modify POCO template to not use them or you can delete Products navigation property in Attribute (if you don't need it).