Entity Framework 4 website architecture - entity-framework-4

Hi I've been given the task of creating an N-Teir website using the Entity Framework 4 and am coming up against some brick walls, more than likely in my knowledge.
My plan so far was to have these layers
Website (application layer),
What I'm calling Name.Framework (BLL),
Name.Data (DAL),
Name.Entities (contains POCO classes and other struct classes used in website/bll,
Name.Common (utility class)
I've tried to use the repository class, but am struggling to make things work how I thought they would. Below are a few examples of what I'm getting stuck on.
If I want to use .include() would this be in my Repository or is this the responsibilty of the business layer? (and I have no idea how this would work in the BLL)
Same question for .Order()? As I understood it this would need to be in repository or at least passed into the repo in some way?!?
Should I be using the BLL to pass in the Context to the repository/data layer? At the moment when I get an entity from the Data layer any navigation properties that weren't referenced in the repo just come back with 'Object Context Disposed', should the Business layer still hold the context etc so that this wouldn't happen?
Or to summarize this HELP!!!
I need to have this in some sort of order by tomorrow (eek!) as the project leader wants to know if we are going to continue with Entity Framework or move to NHibernate as in-house we have more knowledge of it.
Thanks for any help or suggestions
Matt

Looking for something similar myself I found this. Not looked into it too much at the moment but looks promising.

I'm currently working on a web hobby project with EF4 Code-Only, where I have the following structure ([name] being the name of my project):
[name].Web - An ASP.NET MVC 2 project
[name].Web.Models - Custom view models, along with AutoMapper mappings from my entity objects
[name].Models - My POCO classes, and interfaces for repositories
[name].DataAccess - Some interfaces related to data access, for example IUnitOfWork
[name].DataAccess.EF - All Entity Framework related classes and interfaces
I also have a test project for each of the above, plus a couple of projects with helpers and extensions for the tests.
It might be relevant to mention that part of the purpose of this hobby project is for me to learn how to use EF4 with some design patterns of my own choice (the ones that concern EF in this project are the Repository Pattern and the Unit of Work pattern). Another partial purpose is to build up a code base that I can re-use in later projects, and this has affected the division between projects in my application - for example, if I wasn't concerned with re-use, I'd probably have all data access related classes in one project instead of two.

I've implemented a basic EF, poco, Repository, UnitOfWork architecture largely following this article here:
http://devtalk.dk/CommentView,guid,b5d9cad2-e155-423b-b66f-7ec287c5cb06.aspx
I found it to be very helpful in these endeavors. Don't know if it helps you but others might be interested in the link.

Related

Business logic layer in ASP.NET MVC - Architecture

I am fairly new to ASP.NET MVC. I am really confused about the architecture of my project. Let me explain my confusion to you guys:
In my project I have three parts which are know to all of us. These are: controllers, models and views.
Controllers reside inside Controllers folder, views go inside Views folder and models are inside Models folder.
As we all know there are two types of models: data model and business model. The data model has all the data types to be used in the project and the business models do have additional logic related to the project. In addition to it there is going to be a data layer of the application which talks to the database.
I am going to create a class library project for this data layer which will talk to database. Also, Models folder of my MVC project is going to have data models only and I am going to create a different library for business model classes as well.
Now the problem I am facing is this:
Lets say the name of my MVC project is MVCProj, name of data layer project is DataProj and that of business layer project is BusinessProj.
If I define the data types inside Models folder of MVCProj, I have to include its reference in both BusinessProj and DataProj projects. Also, I then have to use BusinesProj classes in my MVCProj. Thus I have to add reference of BusinessProj in MVCProj which results in circular dependency.
I am not sure if the architecture I am envisioning is correct or not. Please help me sort it out.
Arsen's answer already explained very well, but I just wanted to post my own experiences (and that's too long for a comment.)
Your idea of separating Business logic and DataAcess is good. Most projects I worked on are organized in a similar manner.
What I would do in your case is:
1 - Create a project for DataAcess: MVCProj.DataAcess
2 - Create another project only to contain your database Entities: MVCProj.Entities
3 - Add a reference of MVCProj.Entities in your MVCProj.DataAcessproject
4 - Create a project for your business layer: MVCProj.Business:
5 - Add a reference of MVCProj.Entities and MVCProj.DataAcess in your MVCProj.Business project (I'm assuming business layer will call database)
6 - Add a reference of MVCProj.Entities and MVCProj.Business to your MVC project.
See the logic? Each layer is responsible for doing "its job". Now MVC controllers may call business, wich call the database to save the records. All projects share the same Entities.
The "Models" folder on the MVC project is just an example the team provided. In most examples in the web you see people calling the database (Mainly using Entity Framework) directly inside the controllers. This works, but in the long run is very bad to maintain.
Another thing most people do is: You usually don't want to return your database entities in your controllers. Perhaps they include more properties than you will need and etc. In this case you can create what is called a ViewModel. Think of a ViewModel of something like a copy of your Entity class but only with fields relevant to the View. The ViewModels are specific to the MVC project, so they will stay in a folder inside the MVC project. You may call it Models, or ViewModels, your choice.
Not going much further, but with the separation of projects I showed above you can definetly look for a Dependency Injection framework to handle all the creation of instances of the classes for you. :)
Note: It was implied but all projects except the MVC one are just plain old class libraries.
Hope this helps clarify your ideas.
There is no silver bullet in Architecture, all of this is not a must, but depends from the project...
The amount of layers in your application strongly depends on the requirements.
On the one hand additional layer separate the concerns(example: from DataAccess to Business Logic) on the other hand with each level you increase the amount of work, and decrease performance
Regarding your question, it is ok, when one layer depends to another, it is not ok that the third layer depends on the first one...
In your case you choose 3 level, ideally it should look like this
DataAccess, with its data classes in separate project
BusinessLogic, another project, which call data access, and convert result to its data classes
And finally on the model reference BusinessLogic only
I did a write up that I think my help some of your confusion: Entities are not Models.
TL;DR The main source of your confusion here seems to be that you think you need your "data models" (entities) in the Models folder of your MVC project. That's incorrect on two fronts. First, the Models folder is pretty meaningless. You can rename it, remove it, whatever. It doesn't effect your application at all. Second, and as the post I mentioned details, entities are not models. They are, and should be, merely representations of a table structure to give your ORM (Entity Framework, likely) some place to stuff the data it retrieves from the database.
That said, the typical approach is something like the following:
"DAL" class library containing your context and entities. This is where your migrations will go.
A "business" class library that essentially wraps your DAL and provides basically an API that your MVC project can use to get at the data. Depending on the complexity of your app, this is the layer that's most fungible, as you'll often need to draw a fine line between what is "business logic" that might be universally applicable to any application your organization develops vs. "business logic" that is related to the specific application you're developing.
Your MVC project, which will utilize the DAL/Business layer.
In your MVC project then, your Model folder can basically go away, or you can use it for storing view models, instead. It's common, though, to actually create a ViewModels folder for those specifically. However, it's entirely up to you.
One final note. The "business layer", could also just as well be composed of multiple different class libraries. In my organization, for example, we have a library specifically for working with our POS system, a library for connecting to an API we utilize for email lists, a library for working with Elasticsearch, etc. Our web projects just include whatever libraries they need to utilize.

Advice on isolating my nhibernate layer such that I could swap it out with EF potentially

Ok it seems my project setup could use some improvments.
I currently have:
1. ASP.NET MVC3 Web project
2. NHibernate project with Repositories/Mappings and some session code.
3. Entities (models used in nhibernate like User.cs)
4. Interfaces (like IUser, IRepository<IUser>, IUserRepository...)
5. Common (UserService, ..)
Now the issue is that I my nhibernate models now need to implement IUser, which I don't like, but I was forced to do this since my IRepository is generic, and I could use IRepository<User> since User is in another project, so I had to create an interface and do IRepository<IUser>
I will never need to have another implemention of User, so this is bugging me.
How can I fix this while keeping things seperate so I can swap out my ORM?
The IUser interface must be defined in the Entities layer if your entities implement it, not in the Interfaces layer. Also I would probably rename this generic Interfaces layer to Repositories or AbstractRepositories or something. Also I would rename the Common layer to Services if it contains services aggregating your repositories.
So the picture could be:
ASP.NET MVC3 Web project
NHibernate project with Repositories/Mappings and some session code.
Domain Entities (models used in nhibernate like User.cs and implementing domain interfaces like IUser)
Repositories (like IRepository<IUser>, IUserRepository...)
Services (UserService, ..)
I think you should approach this problem from Domain Driven Design perspective. Domain should be persistent-ignorant. Proper implementation of DDD repository is a key here. Repository interface is specific, business-focused, not generic. Repository implementation encapsulates all the data access technicalities (ORM). Please take a look a this answer and these 2 articles:
How to write a repository
DDD: The Generic Repository
Your entities should be concrete types, not interfaces. Although you may never need to swap your ORM (as Ladislav is saying in comments), you should design it as if you will need to swap it. This mindset will really help you achieve persistence ignorance.

Suggestions for Structure of an ASP.NET MVC Application

I am a Java Developer making the transition to the C# world. I've gotten a pretty good handle on ASP.NET MVC (and can compare/contrast it to the concepts I learned for Struts).
However, I'm looking for advice on how to structure my project. Currently, I have two solutions in the project: the MVC Web Application and a ClassLibrary section.
The application uses a tiered architecture: Controllers/Services/DAOs. To make things work "right", I have the Controller and Model classes in the MVC solution, and Services, DAO, and Security in the ClassLibrary solution. Unfortunately, this is causing all sorts of minor issues (example: extending the UserAccount object from the Entity Framework on the ClassLibrary side is ambiguous when I try to extend it on the MVC side for form validation).
The only solution I can come up with is to put EVERYTHING into the MVC project, and organizen what is currently in the ClassLibrary under the App_Code folder. It would solve some issues, but just seems "wrong" to me; my Java projects separated code into a src directory and views (jsp's) into ta webapp directory.
What do some of the more experienced .NET developers think?
Generally in .NET solutions, the best bet is to separate code into different projects only if that code may be useful to other applications, or when the code itself represents a complete solution to some problem domain. A class library that is only referenced by one application project is a waste.
Also, keep in mind that .NET does not allow circular references between objects in two different assemblies (which translates one-to-one with projects usually).
In your example I would suggest that you consider one class library for the model, services, and security... depending on what you mean when you say "services" though.
In most cases, data access is somewhat coupled to the concept of the MVC model, so you might consider putting the data access in there too... but if you have a very cleanly separated data access layer it might fit into it's own class library.
The controllers and views generally should go into the web project directly.
In general, my advice is to split stuff into separate projects ONLY when you have an actual "need" to do so. But assemblies and projects are NOT a good way to represent layers or tiers in most applications. Those are logical concepts that don't always map well to a physical project structure.
If you design your actual classes well and avoid tight coupling, you can usually move code into class libraries later if a real compelling need does arise.
What do you mean by making things work "right"? I find that most issues can be fixed by simply including the namespace in the web.config's namespace import section. When you do that, your models from the other assembly are automatically resolved and they show up in the MVC dialogs, and in intellisense when coding views.

ASP.NET MVC - Solution Layout Suggestions

I have been working with ASP.NET MVC for a couple of months now and I'm still not happy with the layout of my project's solution. I am trying to construct a mid-sized website CMS that is as portable and reusable as possible and there are some obvious problems in the design of it. I am looking for some advice regarding how I should structure my solution in consideration of separation of concerns. I've found a similar question here, but it doesn't really target some of the issues I am facing.
Right now this is how my solution is laid out:
+Project.Controllers - All Controller classes
P+roject.Controllers.Tests
+Project.Core - Utility classes including repetitive tasks and some configuration handlers (this project needs to be better fleshed out)
+Project.Core.Tests
+Project.Models - Model classes, Entity Framework context, and Repository classes
+Project.Models.Tests
+Project.Web - All Views and Content
One major thing I am currently missing is a place to stick my business logic and I feel I've been wrongly placing business logic in my repository classes as well as intermingling it in controller actions. Obviously, I'm very aware of this problem, I'm just not sure where I should placing my business logic in that solution layout. Does my solution structure need to change or can I safely keep that business logic in my Models project? Also, I really don't like that my EF Context is in the Models class, but I don't know of a way to isolate the data layer code from the Entity Classes needed in my model.
How is everyone else laying out their production ASP.NET MVC solutions?
You might want to check out the layout the S#arp architecture project uses or the onion architecture as used in the Code Camp Server MVC reference application. Both projects have had allot of effort put into them by different people to get a good sepperation of concerns in the context of asp.net MVC and domain driven design.
Personally I'm only learning MVC. My experience comes from ASP.NET WebForms but I would go with the layout proposed in the link you gave. The second answer, that is:
Models
Views
Controller
Services
Tests - one for each project.
I would take EF Context and Repositories out of Models and into a data access layer, Project.Data and put your business objects in Project.BusinessLogic (?).
This gives the benefit of putting the two assemblies (Project.Data and Project.BusinessLogic) in other apps you might build on the same domain. That means your next project has a very useful starting point.
Hope that helps,
Dan

How can I extend the Model in ASP.NET MVC and Entity Framework?

In my first ASP.NET MVC applications, the model was a simple O/R mapping between a table and the classes, managed by the Entity Framework.
Now I would like to add some meat to this skeleton, and introduce business methods for the generated classes. What is the recommended approch to this in ASP.NET MVC (with Entity Framework)? My favorite would be solution which also can be used in a service layer, with no ASP.NET MVC references, so that the same domain logic also could be reused in a desktop client.
Technically, I think it should be possible to extend the generated classes in a way which preserves the additional business logic even if the O/R classes need to be refreshed. (This is more a question related to the Entity Framework however.)
Edit: Many thanks for the contributions, and the information about the next version of Entity Framework (4.0). Building two sets of classes, one auto-generated to represent the data in the persistency layer and one for the actual business logic sounds interesting.
Within MVC.Net, the model is the least clearly defined part. In my opinion, it's basically the rest of your application (i.e. anything not related to the View or the Controller). The O/R Mapping part of your application should probably be outside of the "Model" also, as this is more of a data layer. The Model, should really deal in business objects and create views of your data to pass to the View.
There are lots of differing opinions on this, but I think it's best not to think of MVC.Net as traditional MVC Architecture.
If you are using EF v1.0 right now, the Entity Framework is very intrusive into your application, which means that you cannot create POCO very easily. The way you can extend your model is by using the partial class. So when you refresh your model, the partial class you did will still be valid. The Entity Framework team realizes this is a problem , and have improved this in next version (EF V4.0).
NHibernate is much more friendly and allow you easily extend your business logic.
I really think this blog post by Jeremy D. Miller is very good at pointing out the problem.
Abstract your Business Layer out into another project, then pass an instance of it onto your mvc controller using something like structure map. You can then call this Business Layer from your controller to retrieve your business entities (Model) and pass them on to the UI. This will allow you to resuse your Business Layer in your desktop application.
Not only meat but also some clothes and a style could be added to this project to make it seem chic. It depends on the time you have for the project. If you have time, I could suggest you to get a look to TDD and the frameworks that could be used with TDD such as Castle, NUnit, Moq etc.
As you mentioned a service layer is a must for any project but with these kinds of frameworks you could design your architecture more robust.

Resources