title: C# CodeFirst Lazy Loading with MVVM
body: <p>I have a moderate-sized CodeFirst application which has been written using fairly strict MVVM ( which has a C#/WPF front-end and CodeFirst to MS SQL Server backend).</p>
  
  <p>I have written a load of helper classes in the Model, which create the DbContext, load objects and so on. I used to do this by generating a single DbContext per thread (in a static function) and obtaining that reference from the appropriate load function (Person.Load() would call GetDbContext). This worked quite nicely alongside lazy loading.</p>
  
  <p>It got to a point where there were some bugs in my code due to the use of this single DbContext per thread and so decided to switch to the better practice of a single DbContext per work unit, with loading code inside a 'using' statement. There seems to be negligible real-world speed difference.</p>
  
  <p>My problem now is one of lazy loading. Because when the properties on 'Person' are accessed, the DbContext no longer exists, 'automagic' lazy loading does not happen.</p>
  
  <p>What's the best way to get around this? I can manually call the Model in my ViewModel when one of these properties is accessed, but I'm ending up with calls to the Model everywhere and doing things manually that should happen behind the scenes. It also means that things seem less coordinated - I'm ending up with detached POCO's and it seems more of a mess that when I was originally using one DbContext per thread! The normalized structure of the database does mean that there are lots of these sorts of relationships.</p>
  
  <p>The other (very resource-hungry) method could be to store a DbContext with each loaded object so that lazy loading still works...</p>
  
  <p>Thanks in advance for any advice.
  Adam</p>