EF4 and unwanted loading of the corresponding collection using AddObject

I have an odd case where adding an entry causes an unwanted download of the linked collection.

For example, I have queries and sessions. A session can contain many requests. I already downloaded the session and just want to add a new request.

However, when I set up the AddObject call to the ObjectSet of the query repository, SQL Profiler shows the selection query that is executed on all related queries in this session.

Here is the problem code:

this._request = new Request { Action = (string)filterContext.RouteData.Values["action"], Controller = filterContext.Controller.GetType().Name, DateAdded = userContext.Session.DateLastActive, IpAddress = filterContext.HttpContext.Request.UserHostAddress, SessionId = userContext.Session.Id }; loggingService.AddRequest(this._request); 

This last line just calls my service, which in turn just calls _objectSet.AddObject(entity) .

The same thing happens if I try to set a new Request Session = userContext.Session (instead of the above SessionId = userContext.Session.Id ) - the request will be executed when this property is configured, and not on AddObject. Thus, it seems that EF4 believes that it needs an appropriate collection of requests for the session when it is referenced for some reason.

But I do not need related requests in the session, nor are links used or not used. So I'm not sure why EF4 loads them. I went through the code and verified that this was happening on the AddObject(entity) (Profiler shows that the request is being executed on the same instance).

Why is this happening, and how can I stop it?

Thanks in advance.

EDIT: Is it because EF4 is trying to add a new request to the corresponding Session.Requests compilation and is sent and received by everyone else? If so, is there a way to prevent this? As I said, I do not need these Requests, I just need to add them and continue.

+6
source share
1 answer

I assume that you are using the POCO T4 template, which suspects precisely this behavior. The problem is with the commit methods created by the POCO template. Each time you assign a navigation property, a foreign key, or add an object to a collection of related objects, these methods bind the graph of the object. This means that they also update navigation on the associated object. In your scenario, this means that the fixup methods add Request to the Requests collection in Session . Accessing the collection will result in lazy loading. The only ways to avoid this:

  • Disable lazy loading for this operation ( context.ContextOptions.LazyLoadingEnabled = false )
  • Remove Requests Property from Session
  • Modify the T4 template and remove the repair methods.
  • Modify the T4 template and remove the virtual object from Requests ( Session will not support lazy loading)
+6
source

Source: https://habr.com/ru/post/887101/


All Articles