Entity Framework 4 very slowly binds a customer order that has 10,000 orders

I have me at a standstill.

I have a Customer and Order object. The client may have many orders.

If 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 (20 seconds). It seems that the context loads all 10,000 orders before adding this new one.

I currently do not use FK directly, which I suspect might help.

Any ideas how I can improve the situation without a massive refactor?

Greetings.

+4
source share
2 answers

Most likely, the problem is using the T4 POCO template. This template generates disgusting commit methods and uses them internally in all navigation properties. If you change the navigation property on one side, it causes a fix that will try to change the reverse navigation property to match the graph of the object. And here a problem arises. When you assign the Customer property to the Order instance, it will correct the Orders property in the Customer instance, but the patch access property is like any other code and starts lazy loading of all customer orders.

There are only a few solutions:

  • Use a foreign key relationship and set the FK property. This should work for inserts, but it can still cause problems for updating, because to set the FK property to another value, the null property for the navigation property is set, and this will again cause a fix for the previous parent.
  • Disable lazy loading for this operation - you most likely will not need it to create a new order.
  • Change the template and remove the fix
+9
source

Perhaps a different approach might work. When you have a client instance, try:

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

I am not working right now, so I do not have any code to check the structure of the entity (working with self-test objects for the project), to understand whether this makes sense. But adding it to the Orders collection, the entity can resolve the relationship between the order and the client, without receiving all the remaining 10 thousand Orders of this particular client.

+1
source

All Articles