Question

I have a project structured as follows: .Persistence -> .Repo -> .Services -> .Controllers -> MVC3 App.

Each layer has a respective assembly with interfaces and there's also some other assemblies like .Entities, .ViewModels, and common code assemblies.

Persistence - This holds the EF4 datacontext (code-first) and a reference to EF4.3. There's a factory for creating the Context called GetContext() and this factory implements IDisposable. It is NOT a singleton cause I figured that's what windsor would do for me with LifestyleSingleton().
Repo - This holds repositories implementing the repository and specification pattern (http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/).

The other layers are self-explanatory...

Questions:
1. Why does proxy creation have to be enabled when lazy loading is enabled?
2. If I want to set lazyloading = false, can I cast my IEnumerable in Service layer to ObjectQuery in order to use .Include() there?

Was it helpful?

Solution

Why does proxy creation have to be enabled when lazy loading is enabled?

Because lazy loading with POCOs relies on proxy creation. Without proxies lazy loading doesn't work. Therefore the combination ProxyCreationEnabled = false and LazyLoadingEnabled = true makes no sense. The reverse combination makes sense, in case you want to work with change tracking proxies but don't want to use lazy loading.

If I want to set lazyloading = false, can I cast my IEnumerable in Service layer to ObjectQuery in order to use .Include() there?

It depends on what your IEnumerable<T> really is. If it's the result of a ToList() then no (because List<T> is an implementation of IEnumerable<T> but not of IQueryable<T>.). If you just return an IQueryable<T> as IEnumerable<T> you probably can cast to IQueryable<T>. (In EF 4.3 you would use IQueryable<T> or DbQuery<T> rather than ObjectQuery<T>.)

But imho the need for such a cast indicates that something is wrong in your architecture. Using Include is a modification of a query. If your service layer is allowed to modify queries your repository should return IQueryable<T> - this type is made for building and modifying queries.

If your repository is not supposed to return IQueryable<T> you must pass in an expression or a specification into the repository methods which is used to add an Include to your query - inside of the repository method, not in the service layer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top