Architecting ASP.Net MVC 3 with EF - asp.net-mvc-3

I'm trying to architect my MVC web project and I'm running into a bit of a problem.
I am using EF4.1. I've created a DataAccess project with the EDMX file. Then I use the dbContext generator to make my POCO .tt classes.
As it is right now, my Business logic layer can access the POCO classes just fine, but the presentation layer cannot.
I think that I'm supposed to create another level of abstraction and put the dbContext .tt files into their own project so that both the BusinessLogic layer and the Presentation layer can access the POCO classes, but only the BusinessLogic has access to the entity framework. The presentation layer shouldn't need to know anything about EF.
Something like this...
POCO Classes - DataAccess
| |
|---------Business Logic
| |
|_________Presentation
Am I on the right track here, and if so, do I simply cut/paste the .tt files into the new project or is there a way to force the dbContext add-on to create these in my other project?

Your presentation layer doesn't have to know anything about the EF. Just reference that project from your presentation layer to access the models.
However - your presentation layer shouldn't ideally be using any of those POCO models. They should be using ViewModels. I dont necessarily believe in the DTOs here as DTOs have a specific purpose. Your repository/data access can return models but generally those get returned to a service layer. The service layer then would return your ViewModel representation to your controller.
This sets you up nicely for dependency injection as well, since into your controller you just inject your service layer. Into your service you can inject then any repositories you need, and so on.
Ironically I think I may be working on a book for this exact subject shortly : )

Consider sending Data Transfer Objects between your Business Logic and Presentation layers. This would allow you to shape the data for your views and and prevent information from leaking into the Presentation layer (e.g. if you have a field in your POCO that is needed for your business logic but doesn't need to be available in your Presentation layer).
The question is, how would you move data to and from the
presentation layer? Put another way, should the presentation layer
hold a reference to the domain model assembly? (In an Entity Framework
scenario, the domain model assembly is just the DLL created out of the
EDMX file.)
From a pure design perspective, DTOs are a solution really close to
perfection. DTOs help to further decouple presentation from the
service layer and the domain model. When DTOs are used, the
presentation layer and the service layer share data contracts rather
than classes.
A layer of DTOs isolates the domain model from the presentation,
resulting in both loose coupling and optimized data transfer.
If you go this route, also check out Automapper to help with mapping your DTOs to POCOs and vice-versa.

So there are several ways to structure your project. What you are referring to is one way, in which you share poco's between all layers.
Another way is to have your POCO's be in the data and business layer, then create a similar object model that's shared between UI and business layer. Finally, you might also create a third model for the UI only called teh ViewModel.
It all really depends on your needs. If your object model is very complex, then you might need to simplify it with ViewModels.

Related

MVC With N-Tier Architecture

I have been jumping between articles and questions but i can't seem to find the information i want.
When i started learning about MVC, tutorials and articles pointed out that:
*Models: is where you business logic goes
*Controller: is where data-access and handling request/respond happens.
I have been working with MVC for a while now and I wanted to migrate an old simple project to MVC. In the project i have a business and data access layers.
After reading about N-Tier MVC architecture, my understanding changed.
The model in which i usually presumed to be the business domain has now changed to be more of a presentation depending on views. Its true that models reflects the business entities but it acts as another layer over it.
So my question here is the following: Assume that i have an MVC project and i have another two projects, business and data-access. Is the relation in this manner right ?
*A model, will mostly have the same properties as in its corresponding business entity.
*The controller will call the DataAccess-Layer to retrieve data, the data will be returned as business object which will be mapped into a model and then returned into a view.
Model not always corresponds to business entities. Because models in MVC used to reflect entities that will be sent to view. So they may be little bit sipmlier than domain business entities. It is correct that your domain model will be mapped to mvc model.
Second statement I agree 100%.
Is the relation in this manner right ?
My answer is that depends on your project scale and team size, But let me explain you my projects architecture.
MVC: A presentation layer, It is the startup project of the application.
Common: This is a class library which contains a set of core classes, such as helpers, base classes, ... This project is referenced to all other projects.
Repositories: For reading from and writing to a database, I've created a project and named it repositories. This project is a combination of repository and the Unit of Work pattern. Implementing these patterns can help insulate your application from changes in the data store.
Test: Unit tests are written in this project.
Hope this will help you.

MVC / Repository Pattern - Architecture

I have a project in which I am using NHibernate and ASP.Net MVC. The application is intended to allow users to track certain data and then produce views of statistics based upon the data entered. The structure of my application thus far looks something like this:
NHibernate Layer: Contains Repository<T> and UnitOfWork classes, as well as entity mapping definitions.
Core/Service Layer: Contains generic EntityService class. At the moment, this simply defines transaction scope via IUnitOfWork and interfaces with IRepository to provide higher-level data access services.
Presentation Layer (MVC Application): Not yet implemented, but contains the usual stuff plus dependency injection.
I have a couple of questions:
Is it poor design to allow my MVC application to handle dependency injection for ALL layers? For example, as well as dependency injection of EntityService instances into controllers, it will handle the dependency injection of IRepository into the EntityService classes. Should the service layer handle this itself, even though this would mean performing dependency injection in two distinct places?
Where should I produce my statistics? This business logic doesn't seem to belong in my service layer, which, at present, only contains entity type definitions and an interface for modifying and accessing entity properties. I have a few thoughts on this, but I'm not sure which I like best:
Keep my service layer as is and create a separate Statistics project - this is completely independent of the entity types for which it will be used, meaning my MVC controllers will have to pass raw numerical information between my business entities and my (presumably static) statistics classes. This is quite a neat separation but potentially means a lot of business logic still remaining in the presentation layer.
Create a Statistics project; however, create a tight coupling between the classes in this project and my business entities. For example, instead of passing a Reading object's values into a method, I will pass the entire object (or define them as extension methods). This will shift business logic out of my MVC app but the tight coupling seems a bit messy.
Keep all of my business logic inside my service layer. Define strongly-typed subclasses of EntityService, so my services contain both entity-specific business methods and data storage methods, while keeping the entity classes themselves as pure data containers. Create a separate Statistics project for any generic statistical processing and call its methods via my derived service classes. My service classes effectively merge business functions with the storage functionality provided created by IRepository<T>.
I am erring toward the third option but does anyone have any thoughts? Alternative suggestions?
Thanks in advance!
Preliminary observation:
I like the way in which you described your project, I just didn't get why your Data Access Layer (DAL) is called NHibernate Layer: it is odd with all the rest in which you didn't use technology name to describe a logical layer (correctly). So I suggest you to rename it DAL, and use it to abstract your app from NHibernate.
My opinions about your questions:
Absolutely no. It is good to apply Dependency Injection to All Layers. A couple or reasons for which it is good:
1.1 Testing: you can mock DAL interfaces and do unit test Service Layer w/o DAL using another DI config file. In the same way you can mock Service for Web Controllers layer and so on.
1.2 Different DAL implementations: suppose you need different DAL implementation (NOSQL, SQL or LINQ instead of NHibernate, etc..) technologies for different deployment of you project or to scale in the future. You can do that easily maintaining different DI config files.
You can have the same layer deployed in different projects. In the same way you can have a project containing different layers. I think their relation is orthogonal: project is describing a physical (development time and run time) implementation. Layers are logical. So initially I would keep it simple with the third option.
I just don't understand why you saying the following regarding this option:
Create a separate Statistics project for any generic statistical
processing and call its methods via my derived service classes. My
service classes effectively merge business functions with the storage
functionality provided created by IRepository.
I see Statistics as one or more services so you can implement it as namespace with classes inside your Service Layer. And, as any other service, you can inject DAL Repository classes. And, as any other Service/DAL, the Model classes can be shared between different Services and DAL classes.
StatsService.AverageReadingFor(Person p, DateTime start, DateTime end) sounds good.
There are several implementation options:
Using underlying repository features (for example: SQL avg function)
Using Observer Pattern which is implementable also using Dependency Injection
Using Aspect Oriented Programming. See that Spring.Net chapter as an example.
If you have more than one Service Layer instance (more than one server) than 2 and 3 must be adapted for out of process communication using a messaging system.
Just an update - Regarding my second question, I have decided to define an IStatsService<T> which expects an IEntityService<T> to be passed into its constructor. I'll use this for generic statistical processing of business entities and create further interfaces that implement IStatsService<T> where I need more type-specific information.
Hopefully this will help someone who has been scratching their head about a similar problem!

How to create a repository (using EF) so that I can remove the EF reference/DLL from my MVC project?

I would like to create a DataAccess / DataLayer project and encapsulate EF there, so that my MVC project doesn't know that I'm actually using EF. I may decide to use NHibernate in the future, and the out-of-the-box MVC project created by Visual Studio adds EF referece/DLL to the web project.
I cannot access the DbContext from MVC of course, because it needs EF reference.
As a result I wouldn't be able to use Code First data annotations, due to EF being required.
Is it worth creating a repository, or should I keep it "simple" and add EF reference to my MVC project?
It just doesn't make sense to me that I need to add a reference to EF to all my projects, tests and clients that use the context/database.
Thanks
What you are trying to create is the typical layer pattern. At the top you have the Presentation Layer, in the middle you have your Business Layer, and at the bottom (or last layer), you have your DAL layer.
How you design your layers is completely up to opinion and need, but the way I described it above requires you to have 3 different projects. A MVC project, a Logic project, and a DAL project. The DAL project will contain your EF reference and your repository objects. It's then up to you to convert your DbContext/ObjectContext items to POCOs to use them in the business layer. The business layer would know about EF (depending on how you pass your EF objects around), but the business layer would then pass it's own objects (mapping them from your DAL layer objects) to MVC -- thus completely decoupling EF from the MVC layer.
If you are going to use this type of pattern, you should go a step further and include Dependency Injection with a bootstrapped container (crosscutting project using Unity Framework, or something like that).
See Microsoft Pattern & Practices, http://msdn.microsoft.com/en-us/library/ff650706 (Chapter 25 is a good example of layering).
HTH
I choose to implement the repository system in just about all my projects for the exact purpose of decoupling my DAL from any one DataAccess technology or even a specific database.

ASP MVC separation of service/model from view

We are building an ASP MVC3 application, where we are building the service layer and Entity model. A third party is building Views/Controllers.
Now the tricky bit is the Model. Where should it go?
My opinion is the MVC web application will just have View and controller. Our service library will have business logic and EF. But I think we should not expose EF entities directly to the web application. (or should we? ) Instead we should look at the views and create view model classes for each views. This might require creating multiple view model classes for each view.
Can anyone provide their opinion on if this is right design? If so, where should view models reside? should we create another library just for view models?
I would suggest making your models as POCO objects with CRUD functionality- you shouldn't expose the EF entities. This way your service library can be reused in other applications or interfaces if needed.
If the POCO objects you provide won't work directly as view models, then it's up to the team writing the controller to create a view model from your service objects (POCOs). That would probably (hopefully) be a very simple view model, using your POCOs as properties (maybe a view model is a list of one of your POCOs, or a combination of a couple different POCOs).
That's just my two cents...

advice on architecting asp.net mvc applications

I've been using ASP.net MVC for about two years now and I'm still learning the best way to structure an application.
I wanted to throw out these ideas that I've gathered and see if they are "acceptable" ways in the community to design MVC applications.
Here is my basic layout:
DataAccess Project - Contains all repository classes, LINQ-to-SQL data contexts, Filters, and custom business objects for non-MS SQL db repositories (that LINQ-to-SQL doesn't create). The repositories typically only have basic CRUD for the object they're managing.
Service Project - Contains service classes that perform business logic. They take orders from the Controllers and tell the repositories what to do.
UI Project - Contains view models and some wrappers around things like the ConfigurationManager (for unit testing).
Main MVC Project - Contains controllers and views, along with javascript and css.
Does this seem like a good way to structure ASP.NET MVC 2 applications? Any other ideas or suggestions?
Are view models used for all output to views and input from views?
I'm leaning down the path of making view models for each business object that needs to display data in the view and making them basic classes with a bunch of properties that are all strings. This makes dealing with the views pretty easy. The service layer then needs to manage mapping properties from the view model to the business object. This is a source of some of my confusion because most of the examples I've seen on MVC/MVC2 do not use a view model unless you need something like a combo box.
If you use MVC 2's new model validation, would you then validate the viewmodel object and not have to worry about putting the validation attributes on the business objects?
How do you unit test this type of validation or should I not unit test that validation messages are returned?
Thanks!
Interesting.
One thing I do differently is that I split off my DataAccess project from my Domain project. The domain project still contains all the interfaces for my repositories but my DataAccess project contains all the concrete implementations of them.
You don't want stuff like DataContext leaking into your domain project. Following the onion architecture your domain shouldn't have any dependencies on external infrastructure... I would consider DataAccess to have that because it's directly tied to a database.
Splitting them off means that my domain doesn't have a dependency on any ORM or database, so I can swap them out easily if need be.
Cheers,
Charles
Ps. What does your project dependency look like? I've been wondering where to put my ViewModels. Maybe a separate UI project is a good idea, but I'm not entirely sure how that would work. How do they flow through the different project tiers of your application?

Resources