Is Entity Framework a repository - c#

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.

Related

EF6 and layered architecture

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.

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.

n Layered Asp.net app with Entity framework

I am facing the same issue as the one below
Entity Framework 6 and Unit Of Work… Where, When? Is it like transactions in ado.net?
As per the answer, i shouldn't create an abstraction layer over EF, but i want to keep my business layer independent. So i decided to go with the last option, adding TransactionScope. But i read, that it affects the performance. I have kept the IsolationLevel to ReadCommitted. But i am not sure about the performance.
So how can i use EF without adding its dependency to business layer.
My business objects are different from Entity objects.
If you don't want to draw a dependency on EF, you're going to have to abstract it out. The poster in the response you mentioned believes this is too much code, but if you want to decouple the data layer implementation from the business layer it's a necessary evil.
Historically I've gone with a relatively generic IRepository implementation that's generated from an IUnitOfWork such as:
uow.Get<IRepositoryType>()
By using an IoC container (using TinyIoC lately) we're able to handle and swap out our implementations easily, and keep our domain object separate from our data objects.

Shall, I implement Repository, Unit of Work for EF6?

Since MSDN says about DbContext:
A DbContext instance represents a combination of the Unit Of Work and
Repository patterns such that it can be used to query from a database
and group together changes that will then be written back to the store
as a unit. DbContext is conceptually similar to ObjectContext.
Is it not redundant to implement these two (Unit of Work & Repository) when using EF5+?
Can somebody shed more light on this subject?
I intend to build an MVC based application using SQL server and after reading a lot about data access techniques with unit testability, I am kind of lost with the above info!
That depends on the complexity of your project and its requirements. For instance, these two questions might help your decision making:
Will you use any other data sources besides EF that must work along it?
How likely it is that you swap EF for a different ORM or data source in the future?
If you can't foresee changes or you don't need to work with more than just EF then it's probably not worth the trouble.
I would create a Generic repository so you can mock it in your tests more easily than mocking Entity Framework's context directly. But, yes, EF 5+ does implement these patterns as MSDN states.
It's a layer of abstraction. The repository pattern is a collection of objects and a thing to get a collection of objects. Entity Framework knows HOW to get that collection of objects, the repository does not know HOW.
Entity Framework has a lot features that you potentially loose by wrapping it in a repository or a thinner service. If you practise TDD coding against your own classes is often more comfortable than mocking third-party code.
Ayende has a blog post about this.

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