Is there a way to disable LINQ's object tracking features, without also disabling lazy-loaded child associations?
I'm using LINQ2SQL in a set of integration tests. I'm only using LINQ to verify changes in the database, so I want it to act like a simple data access layer rather than a full ORM. To do this,I set set the data context's ObjectTrackingEnabled property to false to prevent LINQ from caching data. This works fine, except that it breaks associations between entities.
For instance, assume two tables WIDGET and CATEGORY, with a FK relationship between them. With object tracking enabled, widgetInstance.CATEGORY is correctly lazy-loaded. With object tracking disabled, nothing is lazy loaded and the CATEGORY property is always null.
How do I prevent LINQ from caching data, without also preventing lazy-loading?
UPDATE: Here's a link to the MSDN page referenced by the answer. Further research also turned up that I can use LoadWith to do eager loading of child data. In my case I just want the data, so eager loading is fine.
According to MSDN:
Deferred loading requires object tracking. Only the following three modes are valid:
ObjectTrackingEnabled = false. DeferredLoadingEnabled is ignored and inferred to be false. This behavior corresponds to a read-only DataContext.
ObjectTrackingEnabled = true. DeferredLoadingEnabled = false. This situation corresponds to a DataContext that allows users to load an object graph by using LoadWith directives, but it does not enable deferred loading.
Both are set to true. This is the default.
You either have to enable object tracking and detach entities (which is doable since you're running tests, I guess, otherwise it pretty much troublesome to detach every single entity of another entity of...), or use DataLoadOptions.LoadWith() or AssociateWith() to eager-load the relationships.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With