1

I have a 3-tier web application wit ha bunch of simple forms. One to list records, one to edit a single record, etc. The works.

I have a DataLayer where my EDMX is. I have an App Layer where my POCOs are. I haev a BusinessLayer with all my controller classes, etc. (not MVC!) I have a UI layer where my web UI is.

The EDMX has many, many tables wit ha lot of navigation properties. Of course, when I fetch the data in one of my controllers, e.g. GetCustomerById(int id), I create the Object context and close it when I'm done.

However, the ObjectContext is out of scope when I try to access the navigation properties in the UI layer.

Should I do (using MyContext = new MyContext()) {... } in the web layer?? that does not seem right. Should I create another set of POCOs that I populate from the entities' data from the BizLayer? What happens when I want to save data entered in a web form? Would I call a BizLayer controller e.g. SaveCustomer()?

My question is, how do you design the web UI layer if I want to be able to properly access the navigation properties of an entity?

Note: EDMX is set to LazyLoading.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
John
  • 3,591
  • 8
  • 44
  • 72
  • OMG this question comes back again and again... :) see my asnwer here, it's not the ultimate truth or the only way to go but I got plenty of consensus so far... http://stackoverflow.com/a/7474357/559144 – Davide Piras Feb 16 '12 at 09:07
  • Thanks. This isn't MVC though. The question for me is if I don't want dependency on EF in the web UI then how do I deal with the POCOs and how to I properly access/save/edit them. – John Feb 16 '12 at 09:23
  • that is all explained in my answer, it applies also to web forms or windows forms or WPF, layering like that you isolate UI from any dependency on EF, NHibernate etc... – Davide Piras Feb 16 '12 at 09:26

1 Answers1

1

You want to use lazy loading in UI but it means that UI defines lifetime of your ObjectContext. There are many ways to achieve this without exposing the context to UI. You can for example use this simple approach:

  1. You mentioned some controller which uses context and disposes it. So make your controller disposable and instead of disposing context in every method use single context for whole lifetime of the controller. Dispose the context in controller's Dispose method.
  2. Instantiate your controller per request. So for example you can create instance of controller in Page.Load and dispose it in Page.Unload.
  3. Use your controller and entities as you want. Whole processing of the request (between Load and Unload) will be in scope of single living context.

Anyway you should not need lazy loading in Web application too much. In your form you usually know exactly what entities you need so you should request them directly with eager loading.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670