Entity framework in a multi layered application - entity-framework-4

Im trying to use EF4.1 in a setup where I would have a DAL (data access layer), BLL (business logic layer) and then a presentation layer (usually ASP.NET web app or console app maybe).
Currently I do all my projects using LINQ to SQL and have a set up that uses multi layers as descibed above.
When looking at EF though all the examples just seem to use 1 layer or maybe 2 layers its hard to find a full example that uses a DAL and BLL.
The closest I've got to what I want at the moment is to use the POCO code generator to create POCO classes and then re-locate these classes into my BLL project - and the .edmx and the object context remain in the DAL.
The problem with this though is the DAL needs a reference to the BLL so that it knows about the POCO classes - ideally the reference would be the other way round. If the DAL has a refernce to the BLL I cant also have a reference from the BLL to the DAL - because you can't have circular references, so I cant do anything with the object context like call the save changes method from the bll.
Anyway I've got in a bit of a mess with it all.
I'm considering doing things in a different way (similar to what I do currently with LINQ to SQL) where the EF entity objects stay in the DAL and I write my own BLL classes that just 'piggy back' onto their DAL object counter parts. That way the DAL can have a reference to the BLL and the BLL.
Sorry its a long question but appreciate people's thoughts, I really have spent hours and hours reading about EF but struggle to see how it can work in a multi layered approach.

Well I've asked myself the same question some months ago.
I've found a whitepaper from Microsoft about layering, and what I can recall is that they consider EF to be a BLL+DAL component in some scenarios.
and in my case, here's what I've been doing so far :
I only create two layer : presentation (ASP.Net) + Business Layer (containing EF classes, EDMX and DB Context)
I manage the DB Context within the Presentation layer (to have more control through Sessions or HttpRequests over my EF-objects life cycle)
In fact, I merge BLL + DAL. But I have to admit I'm not involved in projects with very complex business processes.
I know it's not perfect from an strict architectural point of view, but it works well for the kind of project I have to handle.
In the first times I've been creating the 3 layers but it comes to a nightmare when you have to constantly create 'dumb' classes to map DAL and Presentation..
Depends on your data and business model complexity I guess..

Related

Entity Framework and ASP.NET MVC - how to directly make use of DBContext and DBSet to behave as Repository and Unity of Work patterns?

I am in the process of making project decisions on development patterns for a solution, which involves the use of Entity Framework 6 as the ORM choice,
and ASP.NET MVC 5.
I need insight on how transactions and business logic will be implemented. In respect to layers, I came to an initial assumption for the design where
Entity Framework on top of SQL Server can be considered the Data Access Layer (DAL). On top of Entity Framework, there will be a Service Layer, where business logic and validation will be implemented. On top of the Service Layer, I will have ASP.NET MVC Controllers consuming what the service layer offers.
Let me ellaborate on this initial conclusion drawn as a starting point for defining the architecture:
I want to follow principles to achieve the minimum complexity scenario possible, in respect to layers, abstractions and all the solution components responsibilities. As an excercise, with this "simplicity" in mind, I could just embrace the template "proposed" by Microsoft as when you just create a new Visual Studio ASP.NET MVC Web application, but I believe that does not fit the minimum design scenario needed for an enterprise application, since in Microsoft's template, the controller directly makes use of Entity Framework DbContext and consumes the Data Access Layer, besides the fact that no service layer is present. This leads to several issues, such as extremely tight coupling
between the presentation and data access layer, as well as the so called "fat controller" problem, where controllers become the bloated piece of the software with all the added responsibilities of business logic, transactions, and so on, making it truly a mess to software maintainability with, for example, the most basic principle of DRY (don't repeat yourself) being violated since you would get duplicated code and logic all over your fat controllers.
Ramping up the next stage on the path from simplicity to complexity, I assume it is fair to add a Service Layer to the design, because this way ASP.NET MVC controllers would talk only to this service layer, who would be responsible for all CRUD and validation of CRUD operations, and all other more complex business logic operations. This Service Layer then would talk to the data access layer being represented by Entity Framework.
I would stop there and say the design with these proposed layers is enough, but that's where I need more insight on how to proceed. I need to resolve the question on how would transactions be implemented, if you think of them as a wrapper for a series of individual operations performed by methods responsible for validation and business logic residing in classes inside the service layer. In terms of implementation using Entity Framework, if I get every individual operation performed by a service layer method to issue a .SaveChanges(), I would lose the ability of having DBContext to behave like a Unit of Work, wrapping up a single .SaveChanges() for many individual DBSet operations. In this case, the DBSets may behave like repositories. Many people argue that Entity Framework's DBContext and DBSet are implementations if Unit of Work and Repository pattern, respectively.
In a more objective question then, how can I implement these patterns using directly DBContext and DBSet, without any further abstraction into new generic or specific entity repository classes and unit of work generic class? The implementation needs to rely on the consumption of a service layer for the reasons I have already stated.
I think an answer to that would be just the last complexity leap I feel necessary to get my "least complex viable design".
Let me put a more concrete example to illustrate:
In my service layer, I have 2 methods to implement validation logic for 2 insert operations, with a programmer defined method Insert such as:
EntityOneService.Insert
EntityTwoService.Insert
Each of these methods in their corresponding service layer classes would have access to a DBContext and use DBSet.Add to signal they should be persisted,
in case all validation and/or business logic passes. The desired scenario is that I can use each service layer method call in an isolated way, and/or in groups, such as in a new different service layer class method, such as:
OperationOnePlusTwoService.Insert
This new method would implement calls to EntityOneService.Insert and EntityTwoService.Insert, IN A TRANSACTION-LIKE FASHION.
By transaction-like I mean that all calls must succeed, not violating any validation or business rule, in order to have the persistence layer to commit the operations.
DBContext.SaveChanges() apparently would have to be called only once for this to happen, OUTSIDE of any service layer Insert method implementation. In the
context of an ASP.NET Controller consuming service layer methods, how could that be achieved, without actual implementation of a Unit of Work and Repostory abstraction over DBContext and DBSet?
Any advice please would be very much appreciated. I am not posting this to argue the value of a real abstraction and implementation of Repository and Unit of Work patterns, or if Entity Framework's DBContext and DBSet are or are not equivalent to proper Repository and Unit of Work patterns, that's not the point. My project requirements do not involve in any way the need to decouple the application from Entity Framework, or to ideally and fully promote testability.
These are not concerns and I am well aware of consequences and future maintainability impacts on not adopting full fledged implementations of half a dozen layers and all design patterns possible to make a big world-class enterprise solution.
desired scenario is that I can use each service layer method call in an isolated way ... but that behave IN A TRANSACTION-LIKE FASHION.
This is rather simple with EF, assuming your services are not remote (in which case transactions are not advisable in the first place).
In the simplest implementation, each service instance requires a DbContext to be passed in its constructor, and contributes its changes to that DbContext. The orchestrating controller code can control the lifetime of the DbContext and control its use of transactions.
In practice interfaces, rather than concrete service types are typically used, and Dependency Injection is often used instead of constructors. But the pattern is the same.
eg
using (var db = new MyDbContext())
using (var s1 = new SomeService(db))
using (var s2 = new SomeOtherService(db))
using (var tran = db.Database.BeginTransaction())
{
s1.DoStuff();
s2.DoStuff();
tran.Commit();
}
David

ASP.NET MVC, Layers, Models, Repositories etc

I have some questions after reading an article called Layered Application Guidelines (http://msdn.microsoft.com/en-us/library/ee658109.aspx).
For example, I have an ASP.NET MVC application. In my application I have some Entities (Models), Repositories, UnitOfWork and DbContext. And some Views and Controllers as well.
How to split them into layers according to an article above?
As far as I understand, Views and (maybe) Controllers reside in a Presentation Layer. Entities (Models) in Business Layer and Repositories, UnitOfWork and DbContext in Data Layer.
Am I right or mistaken? I'm very-very unsure about it.
Thanks in advance!
Views and Controllers should reside in the presentation layer. Your models should also reside in the presentation layer. Models reflect a view model that is used for presentation only. Entities should represent data and should not be sent to the View. In the presentation later, the models should be populated from the entities. You are correct in that your DbContext and UnitOfWork should be in the data layer.
The way the layers are separated will depend on the scope of your application. For a small one, Areas may suffice. For a larger project, or a project which may become large, you should look into creating separate solutions for each layer. This is known as an n-tier approach, and can be seen when looking at the excellent example at http://prodinner.codeplex.com/.
View models/Views/Controllers - presentation layer
Entities - business layer
The repository mediates between the data source layer and the business layers of the application
The DbContext Represents a combination of the Unit-Of-Work and Repository patterns, so if you are implementing a repository and unit of work on top of it could mean that you should consider to limit your abstractions. (This last point may not apply in your case, I couldn't say without knowing more about your design).
Entity Framework entities (along with the framework) are your data layer. In many applications they also become part of your business layer - and it is debatable whether or not this is good (I personally don't like that, but when you abstract it with say the repository model there is a good argument that you are losing some of the benefits provided by EF).
Depending on how you separate out your code (and it sounds like you are using the repository pattern) you may have a repositories containing some business logic, or have a services layer as well (my preference for 3 tier applications) where business logic (mostly) happens.
I would argue that you should be considering View Models as well as part of your presentation model - but if you are using MVC and data-annotations (which are excellent for this job) to validate your model you have just piled a bunch of business logic in to them.
The most important place to prevent business logic from creeping into is your presentation layer, and most importantly your Views and Controllers. The approach to how you structure the rest of your application depends heavily on the framework you choose, the scale of your application and the deployment structure of the application.
So to be as clear as possible this is what I do*:
Views <--Presentation layer only
Controllers <--Presentation layer only (might end up with slightly 'fat' controller in some instances, e.g. .NET Membership login)
View Models <--Presentation layer, but if doing validations here often business rules are also being tested.
Service Layer <--Business Layer if used
Repositories <--Could be Data layer only, or mix of business layer. If you do the repository pattern try and avoid exposing your DbSets directly, as this immediately defeats the abstraction you are attempting to provide (potential exceptions to this, e.g. - .Net Membership)
Entities <--Data layer, possibly with also business logic depending on how you structure your application.
*Not to be taken as authoritative

EF code-first how to use POCO objects in client layers

I'm new to asp.net MVC and EF, so excuse me if my question is not clear or easy.
I have read some tutorials about EF Code-First approach and now I'm trying this tutorial Getting Started with EF using MVC.
Using Code-First approach I'm using the POCO classes to define my DB model, DB logic, DB validation, UI validation and some UI logic. So I can use these classes(or objects) in my presentation layer or use them as JSON objects when dealing with Web-Services(or in JavaScript code).
My question: Isn't that mixing some logic together? I mean shouldn't I use like special view-model classes for presentation and these classes should have the UI logic and validation ?!
Is it good practice to send the POCO object to the view(or to the client in general) ?
Finally i need some guidance on how to organize my project layers or folders? I see many ways and I'm confused about what to choose or what format I should base my own on?!!
You should not use your data entities in higher layers of your application. Transform/compose/copy data from DAL into view model or business classes using a library like Automapper. This keeps the layers of your application independent and hides your database schema from end users.
Keep in mind that MVC is only concerned with presentation, all real work should happen in other layers of your app. I try to keep layers independent and use a little bit of glue code to bundle them into an app. I may write data access and business logic layers when working on MVC project, but then re-use in a command line utility. There are a lot of books that talk about writing quality code. I personally found Clean Code, Code Complete 2, and Design Patterns extremely helpful.
As LeffeBrune said, is bad practice to show directly your data entities to the presentation layer, you can try to expose some interfaces in form of project services that return the view model to the controller. This can help to keep the layers separate, and implement Unit of Work pattern and some other cool stuff.
You can start reading the Scott Millet Book
ASP.NET Design Patterns
for a starting point in designing a good layered application, here his blog.
You can define interfaces in your business layer which your EF entities can implement; the business logic doesn't know about the actual implementation. To do this you need the data layer to reference the business layer which means you're inverting the dependencies - you then use an IoC container to bind the interfaces to their implementations. ...but yeah that's one of many, many ways to go about it.
The thing is, with single responsibility in mind, your entities shouldn't worry about UI stuff - this can mean your interfaces also need to be implemented by "view model" classes, which implement things like validation and other business & presentation concerns.
Your questions require a lot of discussions.
Choosing infrastructure for your project is a complicated issue that depends on lots of factors. There are some design patterns that address different requirements in a project which involve you or your team in multiple concepts and technologies. I recommend you two valuable resources that help you understanding software architecture focused on .Net technologies.
CSLA.NET : The CSLA .NET framework is an application development framework that reduces the cost of building and maintaining applications. Rockford Lhotka, createor of CSLA.NET, has some books that deeply describe an optimal infrastructure of a project; all of your questions have answered in his books.
Microsoft Spain - Domain Oriented N-Layered .NET 4.0 Sample App: the project/sample is willfully restricted to .NET implementation of most used patterns in N-Layered Domain Oriented Architectures based on simple scenarios easy to understand (Customers, Orders, Bank Transfers, etc.). The project/sample is very well documented and all of your questions , also, have answered in the project.
All in all, view-models, POCOs, layers, etc. are concepts that have root in software architecture and I believe that they can not be described in short.
What I normally use is a POCO layer to use in my data access and a view model layer to use in my views just as LeffeBrune said.
All my layers use POCOs and the controllers are responsible to construct the view model that each view needs.
To get this work more automated I use automapper.
So my solution structure gets usually to be like this:
Model (POCO)
Data access (NHibertante)
Service (Business Layer)
Web (UI)
ViewModel

Improving Asp.net MVC Layers Arhitecture

I want to make a solid architecture for my MVC Project.
Currently, project has:
Database Objects (linqToSql)
ViewModels used for views
one Repository used for
- reading / editing / deleting database objects
- creating ViewModels for page
- other general functions
My initial structure is:
MvcApplication (MvcApplication.Common, MvcApplication.Domain, MvcApplication.Models)
- containing all the views, controllers, repositories
MvcApplication.Domain
- containing linqToSql data file
MvcApplication.Models (MvcApplication.Common, MvcApplication.Domain)
- containing ViewModels
MvcApplication.Common (MvcApplication.Domain)
- containing helper functions, and Enums
Can you advice me creating a better architecture for this project?
Which layer should i remove or not?
Should ViewModels be in the Domain Layer?
Viewmodels are the purvey of the implementation of the views. I do not feel as though viewmodels should be in the domain.
I would do the same thing with data access. I separate that layer, and only have the interfaces for persistence in the domain. I can then inject my data access at runtime. YMMV there though. Depends on the likelyhood of you swapping out the DAL later. Same with services. Interfaces for the services in the domain. Separate assembly for implementations.
DAL abstraction like this becomes VERY handy during testing, So i can run my unit tests against mocks, or a different storage mechanism completely.
I don't know about you but I hate having my logic tests tied to some database someplace. With multiple people running tests, how can i be sure of the integrity of the test DB, unless i do sql express?
I can't even tell you the number of times abstracting the services like that have saved my bacon. What, this services is slow because its all sync? Lets change the service implementation to shove a message in a queue. No changes to the application layers or anything.

ASP.NET MVC Model & Business Objects

I am looking for some guidance on how to incorporate business rules into an asp.net mvc application and how they relate to the model.
First a little background so we know what kind of solutions are relative for this question. At work we use WinForms, MVP, BusinessObjects, DataAccessObjects, and DataTransferObjects. The boundaries of the layers use DTOs to send parameters to methods and as return types, or return List types.
Right now we are adding a facade layer to translate the DTOs into Domain Objects for the UI to work with, since the architect does not like how using DTOs in the PresentationLayer is working currently. I am comfortable about all of this in theory aside from it being practical or not.
I am making a website for fun, but for considerations lets say it serves the same amount of traffic as SO, something like 60,000 hits a month last I heard. I am comfortable with the mechanics of the controllers and the views, and how the model integrates with the two.
I am using NerdDinner as a sample for building the site and I follow the Repository pattern implementation in the examples. What I don't get is how to incorporate business objects into the mix.
I hear people talk about LINQ as the DataAccessLayer/DataAccessObjects. If I force all of my requests though the business objects as I am used to I have introduced some weird dependencies. Both my UI and my BO have to know about my DAO.
What would kind of make sense is to use the LINQ classes as a true DAO layer, hide it behind the BO, and have the BO transform between POCO and LINQ objects.
My only concern there is I am fine with binding my UI to LINQ classes, and don't really need all the extra work, I am happy with a thin lightweight approach as in NerdDinner.
So what I have essentially is the Repository that is instantiated in the controllers that takes and return LINQ objects. My business objects have static methods that just take LINQ classes and perform some calculation, say apply a certain states tax %, or w/e.
Since a lot of these calculations have to be done across the results of the repository I am thinking of combining them into one central area, like a facade layer, but one that just does transforms against the data and not translating to other objects sets (DomainObjects <-> DTOs).
Should I do that, or should I say that those business methods really are part of my model and that they should be in the repository methods that return the objects?
From a design standpoint I would design it like this. Of course naming is just for the purpose of this post you don't have to name your DAL and BLL ..Repository and ..Service.
Have repositories (or one) where your data access/queries should be happening. It should ideally just contain queries (compiled or not). I personally have a repository for each data type to help keep queries separated.
The next layer should be your business layer which I like to call services. These classes are responsible for all logic regarding validation, prep steps and anything else needed to be done to get the consumer of the service the information it needs. As with an ASP.NET MVC app I have my services return view models which are then directly passed into strongly-typed views. With my services I usually group them logically together instead of one for each data type.
This is a great design because it keeps your data access code and presentation code nice and thin and most of the logic where things can go wrong is in your service (or business) layer.

Resources