Lazy Loading

Aug 5, 2013 at 5:01 PM
How do you turn on lazy loading? When I use Repository.UseLazyConnection(), I get a null reference exception when I try to look up something.

using (MyContext context = new MyContext())
 InvoiceRepository rep = new InvoiceRepository();
 Invoice inv = rep.FirstOrDefault<Invoice>(a => a.InvoiceId == 93984);//null exception here

with public class InvoiceRepository : RepositoryBase<MyContext> and connection string in app.config. If I leave out the static call, it works OK, but does not have Lazy Loading enabled.
Nov 6, 2013 at 12:01 PM
That's correct!
In the TransactionAddEntitiesTests test class i placed the following remark:
If you are using ServiceLocation or IoC and cannot use constructor arguments use the static UseLazyConnection field to enable lazy loading the DatabaseConnection.
Don't forget to use _productRepository.SetConnectionString(string connectionString). Otherwise no connection will be made to the database server.

So if i look add your code is should be something like this (not tested).

// Statically enable lazy loading the connection. Use this when using ServiceLocation or IoC where constructor arguments in someway or not supported.

What this basically does is to store the UseLazyConnection setting in memory (not persistent).
After initializing the repository you need the set the ConnectionString if the ConnectionString differs from the Context name. So if you have a connectionstring name other than MyContext in your app/web.config, tell the RepositoryBase wich ConnectionString it should use.

Also a sidenote. You are using a disposable MyContext and also a new instance of InvoiceRepository. This seems like double initializing a Context. If you look closely at the Documentation you should notice that a RepositoryLayer should implement the RepositoryBase<Context> abstract class,. You can than initialize this new RepositoryLayer as a disposable object. This also ensures closing the connection and releasing connection pools held by SqlServer.
Documentation will be updated with this scenario.