w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
C# CodeFirst Lazy Loading with MVVM

One static DBContext is indeed generally not a good solution (especially if you have more than one client that accesses to the DB), so the refactoring you've started definitely makes sense.

Now you have a problem with lazy loading, because once you've reached the end of the using scope, you can't launch a SQL request anymore as the context has closed its connection to the DB server when it has been disposed.

The solution you're talking about

The other (very resource-hungry) method could be to store a DBContext with each loaded object so that lazy loading still works...

is actually what's happening under the hood. Each loaded entity that allows to lazy-load one of its navigation properties is related to Entity Framework (that's those proxy-object of a type generated at runtime that inherit from your POCOs), so it actually holds a reference to the DBContext already.

Which means, if you don't dispose your DBContext manually (with using), lazy-loading will still be available. This wouldn't be the solution to all your problems though, because you probably would have then to deal with multiple entities coming from different contexts, and this simply won't work easily (for example you can't add one entity coming from DBContext instance A into DBContext instance B).

Now, what's the solution then? Well, it probably will be complicated.

You currently have a 2-tiers application, i.e. your heavy WPF client directly communicates with the database. Lazy-loading is enabled, which means everywhere in your code (especially in the ViewModels), a SQL request could be sent to the DB server. This is actually far from the unit of work pattern that better works with a stateless 3-tier application. In such an application, each time you call a service you have a new "unit of work" and a new entity context instantiated.

If you were starting a new application, I would say: go for a 3-tier stateless application, shorten the EF context lifetime as much as possible, deactivate lazy-loading and work with detached entities everywhere in your code.

Now if you have already a lot of code, you probably have two options: either refactor it all with those ideas about context lifetime in mind, or make minor modifications to your current code to only fix the bugs you have right now with your context-per-thread pattern.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.