I'm building an ASP.NET 4 web application using EF4 and I have tables like this:
开发者_StackOverflow社区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.
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).
精彩评论