Question

I have a few questions regarding decoupling my domain layer and data layer in an MVC3 web application using entity framework as the data access layer.

As it stands right now my controllers are completely dependant on the EF classes and after spending most of the day reading up on dependency injection I am trying to decouple them.

The first question I have is - do I need to effectively duplicate all of the EF classes into my business layer? I obviously cant use the EF classes any more so it seems to me that I need to create a duplicate of every table class in use to get this working. Is this right? So for example if I have 50 EF classes representing 50 tables in my DB, do I need to create 50 new classes in my business layer? -> and then maintain them indefinitely? This sounds like a lot of work.

Secondly, am i correct in assuming that the dependancy gets flipped around and instead of the business layer being dependant on the data layer, the data layer ends up becoming dependant on the business layer?

Was it helpful?

Solution

For the duplication of your entities... it depends the version of EF and the approach you use.

If you use POCO entities, then your model is not related to EF as your entities don't inherit from EntityObject. So you wouldn't have to duplicate your entities. At runtime, thanks to proxy entities, EF will generate dynamic types that inherit from your POCO and add all the EF plumbing for lazy loading...etc.

In any case, do note that because of ASP.Net MVC, you'll always end up by duplicating some model classes into what's called view models, so you can strongly type your views.

Secondly, am i correct in assuming that the dependancy gets flipped around and instead of the business layer being dependant on the data layer, the data layer ends up becoming dependant on the business layer?

No, the data layer shouldn't be aware of the business layer.

OTHER TIPS

You can put your model classes in a separate assembly to your context.

If you do that, your data layer, business layer and website can all reference the model assembly, but you can isolate the other dependencies - e.g. the website assembly won't have a direct reference to the data layer, which means it doesn't have to reference EF either.

If you're using code first, this is simple.

If you're using database first, then remove the reference to your model .tt file from your context assembly. Don't delete or move it, but add a link to it in your new model assembly.

To add a link, right-click your project in solution explorer and choose "Add -> Existing Item". You then get a file chooser dialog. The "Add" button on that dialog has a drop down where you can choose to "Add as link".

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