开发者

Entity Framework 4 very slow linking an Order to Customer who has 10,000 orders

开发者 https://www.devze.com 2023-03-13 08:07 出处:网络
This one has me stumped. 开发者_开发技巧I have a Customer and Order entity. the Customer can have many Orders.

This one has me stumped.

开发者_开发技巧

I have a Customer and Order entity. the Customer can have many Orders.

Where the Customer has 10,000 orders when I create a new Order and set the Customer property (Order.Customer = customer) there is a LONG delay (20s of seconds). It appears that the context is loading all 10,000 orders before adding this new one.

I am not currently using FKs directly which I suspect may help.

Any ideas how I can improve matters without a massive refactor?

Cheers.


The problem is most probably that you are using T4 POCO template. This template generates nasty fixup methods and use them internally in all navigation properties. If you modify navigation property on one side it triggers fixup which will try to modify reverse navigation property to make the object graph consistent. And here comes the problem. Once you assign Customer property to the Order instance it will fixup Orders property on the Customer instance but fixup access property as any other code and triggers lazy loading of all customer's orders.

There are only few solutions:

  • Use Foreign key relation ship and set FK property. That should work for inserts but for update it can still cause problems because setting FK property to another value will set null to navigation property and that will again trigger fixup for previous parent.
  • Turn off lazy loading for this operation - you most probably doesn't need it to create new order.
  • Modify template and remove fixupus


Maybe a different approach might work. When you have a customer instance try:

customer.Orders.Add(new Order(){parameter1 = value1, parameter2=valu2, etc.})

Am not @work right now so don't have any code by hand to check entity structure (work with Self-tracking entities for a project) to see if this makes sense. But by adding it to the collection of Orders the entity might resolve the relation between order and customer without getting all the other 10k orders of this specific customer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号