EF6 and layered architecture - c#

I know this question come back again and again, I read a lot about it, but I can't find an answer to my question.
I dont have a lot of exp on asp.net mvc but I already did a project using ef, repository and uow pattern.
In my last project, I had several layers including :
Web (project MVC)
BLL (my business layer)
DAL (data acces, with ef context, repository and uow implementation)
Now, I want to start a new project, with EF6. I read that uow is not need and I want to give a try.
So far I understand that you must pass your dbContext to your services and your services to your controllers, am I right ?
So you must have a ref to entityFramework in your service layer too ? Still right ?
And because of identity implementation, you need a ref to entityFramework in your UI too.
So what's the point of layer anymore ?
If I read this microsoft guide, all I have to do its make a folder to my DAL and other layer ?! Dont seem right to me ... But maybe ?
I read this post too, who seem to confirm my opinion. And if you add unity and configure it in your UI, its just more ref in your UI :)
So my question is, if you must start a new project now, with EF6, asp.net MVC5, what will you do ?
Am I right to want to do layer ? Or just go on with my MVC project only ?
The ONE thing I miss, is a tuto who explain step to step how to start with microsoft MVC 5 template and transform it with layer, decoupling identity, and finally no ef ref in my UI. Is this thing exist ?

There is no silver bullet here. Some people do it one way, some - the other. Depending on level of abstraction needed. I used to have 3 projects:
Web
Core/Business (Services)
Model/EF/Domain (Entity Framework context and models)
And it's fine if Web has reference to Domain or EntityFramework. Web can return EF Models (just to avoid code duplications). And if you need more complex model, you create ViewModel.
I don't recommend using UoW or Repository pattern (unless you really need it). EF context is already an implementation of UoW pattern. If you want to implement repository pattern with Entity Framework, don't expose anything related to EF in the interface e.g. SaveChanges(), Dispose() as in this case you will not take advantage of repository pattern benefits.
So this is how I would build typical small/medium ASP.NET MVC + EF website. But like I said, everything depends on level of abstraction needed. Abstraction level is proportional to amount of code needed to write. So think first and keep it simple. Good luck.

I like the repository pattern very much, since it abstracts your actual data store from your client application. The front end doesn't need to know where the data comes from, it can be either from frameworks such as Entity Framework but it could as well be a simple converted DataTable. This is a generic approach and you can reuse it for all your future projects if your repository framework has passed all your tests. This tutorial gives you a good view on how to implement the combination of UOW and Repository pattern.
Basically your client application (=MVC) doesn't need to have a reference to Entity Framework, it is sufficient for your service layer to have a reference. You then use this reference to pass your own DbContext to the repository layer (assuming that you have written a repository layer for Entity Framework), ideally through DI containers like Unity.
Of course, there is a lot of discussion about whether or not to use the repository pattern with EF (as it already is an abstraction of your database) but I think it's a good exercice of creating and using reusable components.

Related

Is Entity Framework a repository

In the sense of application layers, I have a hard time figuring out, how to place Entity Frameworks DbContext. It seems to me that it aims to replace the repository layer, but on the other hand it doesn't really work like a more basic repository, which is implemented via an interface, making it easy to swap later.
So I found a lot of good posts on the service and repository layer (e.g. this post), but it doesn't seem to answer where Entity Framework fits in this pattern.
Should I add a repository layer on top of Entity Framework or should I just use DbContext in place of a repository, in my services?
You need to ask yourself why would you want to abstract away your data-access layer.
The answer would typically be:
Unit Testing
Replacing the layer with another DB / persistence technology
Many are arguing that the 2nd argument is utterly false because:
Replacing that layer would usually have a much wider effect on your application than just configuring another implementation
It rarely happens and doesn't worth the effort
All in all, I tend to agree that testability should be your main concern and in the case of EntityFramework you can:
Use EF Core with its built-in InMemory provider
Use EF 6 and mock all the methods and DbSets in your context (by marking them as virtual).
And, to answer your question title: Yes. DbContext is already acting as a repository.
EF isn't a layer, it's a data access technology.
EF calls should be written inside a repository, which serves as an abstraction to the service layer so that the service layer doesn't care if the data are stored in a database or somewhere else.

How to implement business logic in MVC 5 with EF6

I've read the MVC5 with EF6 DB First tutorial. With this tutorial, it will generate code (controller and view).
I have created 3 projects in VS:
+ AdminWebSite
+ PublicWebSite
+ EntityFramework
And I've question, where should I implement the business logic, and share it will multiple website (Admin & Public)?
The business logic may include:
Logic with database (i.e. Transaction with multi-table)
Logic with SharePoint info
Logic with Email Server
EDIT
Typo, should be 3 projects instead of 3 solution, but it should be similar case, which AdminWebSite and PublicWebSite have add EntityFramework as reference.
EDIT 2
Before the MVC3, I will create a class project which includes all business logic, and also the Repository class. So that every WebSite or WebServices can use the same business logic (but I'm not sure is it the best practice).
But when move to MVC5 with EF6, the repository and unit of work seems gone. And don't want to implement repository for every table, which some tables just for direct CRUD without business logic.
I hope this can clarify the is Too broad.
Have a look in to this:
http://dombrovsky.github.io/EntityHooks/
It looks like a framework that is designed to work with EF6. It should allow you to write custom business logic when a certain event occurs like when a record is inserted, or updated.
You can utilize Projects under a solution.
I usually have the database layer in a separate project (Class library/DLL) and let other projects refer to it. This way you have only one copy of the ORM (Entity Framework) simplifying any changes in the database model. I also create a database project (if SQL server) that holds the actual schema definitions including tables and stored procedures. This is a great way to make changes in the schema and deploying it.
Anytime a significant enough portion of the code can be re-used it is usually a good idea to make it a class library and have client projects refer to it.
One solution include Web project 、BLL project 、 DAL project,web project contains publish and admin
I would not have a project named EntityFramework, I would suggest that you replace this project with a project named Infrastructure. This infrastructure project would contain classes that depends on external sources like EmailSenders and DAL classes like EntityFramework classes and other stuff that you for some reason in the future might want to replace with other external services.
Your business logic should be stored in a Core project. This core project would not reference either the web projects or the infrastructure project (but the web projects would reference both the infrastructure as well as the core project). If you need an EmailSender in the core project you reference an interface like IEmailSender, which is located in core as well.
This is basically the structure I would suggest:
AdminWebSite
PublicWebSite
Infrastructure
EF
Log
Messages
SharePoint
Core
Test (This project contains all your unit and integration tests)
I really suggest that you read up on using Dependency injection. When you understand DI, the separation of core and infrastructure will make sense and you see how these can use each other without any hard references.
If you dont want to use UoW or Repositories, I would suggest that you move EF to core but the infrastructure project is still very much valid for other external services.

Do I neet Unity of Work and Repository patterns when working with Entity Framework?

So at my job I was pointed to http://www.codeproject.com/Articles/990492/RESTful-Day-sharp-Enterprise-Level-Application#_Toc418969121 and was told to learn these patterns and implement them in my solution.
What confused me was that these things were before entity framework 6 and from what I understood, Unity of Work is used to optimize database performance by grouping queries together. Since EF6 has already these optimizations, should I still implement these layers? I get that the layerness helps with modularization and switching of data source. Does that mean that EF6 is too complex to implement with these patterns and should ADO.Net be used directly or something like that?
EDIT: I've noticed that this added layer allows usage of mock data sources. Not sure how useful this is because of the need to add another layer of apstraction
"Unit of Work is used to optimize database performance by grouping queries together." - This is not correct. Unit of Work is there to collect related operations together into a single transaction which is then committed or rolled back as a whole. It tracks changes made to objects so that required database operations can be deduced automatically and performed on your behalf.
When you work with Entity Framework, you use it to create DbContext from model. That class is both the Repository and Unit of Work, so you don't have to do anything special. Things only become more complicated than that when your project becomes so large that DbContext becomes more of a burden.
Repository is used to abstract your application from datasource, but since EntityFramework implements this pattern by itself and gives you a possibility to change data source seamlessly, there is no neccesity to add one more layer of abstraction.
You will just limit EF possibilities, while creating something like GenericRepository<T>. And nevertheless you won't be able to replace EF by another library with no changes to your code, even if you implement such a layer. (Some queries written for EF will fail for NHibernate, for example).
Just don't use DbContext everywhere in your application (inside UI code at least), use it by your data access layer (services with business dependent methods or something in that way).
Even for scenarios, where some cloud data storage is used (which EF won't be able to handle seamlessly), there is no neccessity for that layer, it's better to introduce separate classes and use them explicitly, because you cannot fit db and cloud interaction into one abstraction, it will start leaking at some point.
Entity Framework is a UnitOfWork/Repository pattern itself. If you need to abstract yourself from EF, then you could implement a layer on top of EF with your own UoW/Rep pattern.
This is good if you want to replace EF at some point in your proyect.
The cons? I think that building a UoW on top of EF gives you a redundant architecture and you will end up writing more code for something that maybe will never change.
In my current proyect, the main structure is very common, with a Data layer (with a sublayer for the Entities) for EF, Logic layer (where I put all the Business Logic) and the View layer (It can be web, or whatever). With that structure I directly invoke EF in the Logic layer.

Where to put Business Logic classes in an Entity Framework - ASP.NET MVC 4 Solution?

I have a Solution with one project is Entity Framework and have my ASP MVC project, I looking for some advice or opinion about the idea of create in top of my POCO objects and the DBContext, a Business Logic Layer with static classes that have the all the methods (example a ContactBLL class with GetContactByID, GetAllContacts, GetContactsByType) to allow the access to the model data and that can be accessed in the Controllers Actions. In that way I don't have to put the implementation code of this methods in Controller Actions methods, and it can be reusable invoking this methods in other Action Controllers. I will appreciate your opinion because it could guide me to respond a question I've asking to myself around a week based in the answer to this one (about where to define the DBContext and how use it).
You can create different projects according to core functionality.
Data Access Layer(DB context and repository etc.) you can make Project.DataAccess, it will have only db context class and repository.
Business Logic Layer(Project.Business) it will have business logic and make call to data access layer.
UI Layer(Project.WebUi) it is mvc project.
and so on.
for detail info you can see this http://prodinner.codeplex.com/ code
Create separate class library for your POCO,
then create another class library for your repository, this should
include only the interfaces needed for your repository
and the implementation will be on another class lib like Project.EF,
Project.NH which will include Entity Mapping, Migration, Repository
implementations. but in reality, chances are you wont be changing
your ORM lib once it was implemented because it will just cause you
a lot of headache(just my 2cents).
you'll create your business layer(class lib) and
web project as separate lib. Models folder of your MVC project will contain your ViewModels.
this is what Im using right now and of course not the best structure, it just something that Im happy with :). hope it helps.
In general, there are four standard projects in a ASP.NET MVC - Entity Framework solution. They are 1) MVC, 2) Core/Business Logic Layer(BLL), 3) Data Access Layer/DBContext (DAL) and 4) Common/Utility.
Standard MVC project consists three main elements which are Model, View and Controller. However, middle to complex solution usually cuts off the Model element from MVC project and moves it back to BLL, we call it as ViewModel(POCO). Following this structure, MVC project is now responsible for employ/use the services from BLL and control the UI through controller.
Business Logic Layer (BLL) is the core of implementing business logic. It is responsible for serving request from the MVC project and work with DAL to persist data. As said above, BLL is the place to define ViewModel, its relations as well interface/ abstract class to support implementing design pattern. Viewmodel(POCO) is likely mapping one-one to data entity at DAL but we do not use the data entity directly on View. Following this structure will help to increase the customization on ViewModel like adding constrains
DAL is the place for DBContext and its data entities.
Common project consist of shared functions like Logging which is used in 1) 2) and 3)
Please read more at
https://www.codeproject.com/Articles/70061/Architecture-Guide-ASP-NET-MVC-Framework-N-tier-En
https://chsakell.com/2015/02/15/asp-net-mvc-solution-architecture-best-practices/

Entity Data Framework and Web app architecture

I Am creating a web application and first use Entity Framework. I created Entity Data Model and now I am not sure, how to proceed now.
Premise: My database is really simple (Rating, WebPage, Visitor) and database tables corresponds to the business objects.
My suggestion is 3tier architecture but how to make it?
It is good idea create partial classes with the same name as Entity Framework objects (Rating, Visitor) and declare here new methods (GetAverageRating()...)? Or is better create some VisitorProvider, RatingProvider and place logic here?
It is better use EF objects in BLL and Presentation Layer or I should create my own BO objects on my BLL layer and transform EF object to BO?
I'm think, it is more practical use static methods on my DAL than instantiate classes on BLL. Do you agree?
Can you recommend me some best practices? I have many ideas how to create it, but I do not know what is the right.
3 layer architecture is quite popular but what it really means?
Presentation layer
Application layer
Database layer
If you ask what each layer means you can be pretty sure you will get several different answers. You can further divide each layer into sublayer and build layered hell like:
Client side presentation layer
Server side view layer
Controller layer
Service facade layer
Service layer
Domain objects layer
Repository + Factory layer
ORM layer
Stored procedure layer
Database view layer
Database table layer
WTF? That is just example that application can be easily over architected. It can go even worse if you insist that only neighbours can exchange data and if you decide to add special type of objects to be exchanged between layers instead of flowing sing set of objects through multiple layers.
Add layers which you need to make you more comfortable with developing the application and which will do reasonable separation of concerns and maintainability needed for the scale of your application. You can simply do the most simplest application which will be used just few weeks and must be developed as fast as possible. In such case you can do that within few days simply by using ASP.NET web forms and data source controls (or ASP.NET dynamic data). It can be badly extensible but in such situation it is exactly what you need to implement application quickly. Writing layers and doing all the stuff around maintainability and extensibility is reasonable if you need it. Another quick prototyping technique is ASP.NET MVC Scaffolding which can create quick multilayered skeleton of the application which can be further modified.
Both approaches are correct and it only depends on the approach you like. The first is called active record pattern but it is not used very often with entity framework. The second approach is more popular. You can either use EF directly in some middle class which you called Provider (common name is also Service). This class will do both data access logic and business logic. In more complex applications developers like to somehow wrap EF to separate class following repository pattern and call the repository either from service or directly from web app. code behind or controller (depending on amount of business logic). Try to do it without repository first. My personal opinion is that people should start to use repository only once they understand EF itself.
Again both approaches are correct. In a simple application it is fully acceptable to create EF model with POCO classes (EFv4.x) and use them in all layers. If you are using ASP.NET MVC you can find that you need special classes as view models to fully represent needs of your individual views. In a more complex application you can have separate objects exposed from a business layer - this is especially used if the business layer is exposed as a remote service (WCF).
It depends how you write these DAL methods - it is absolutely necessary to not share the EF context among requests! It also depends if you want to write some test or not. Layer defined by static methods is something which goes directly against testable architecture where you want unit test just single layer (unit testing with EF can be hard). It also depends if you want to use dependency injection which is based on instances.

Categories

Resources