I've faced some troubles with context in EF in ASP.MVC2.
I thought that best way to improve some operation on DataBase i've created Repository. My repo class adds, deletes, select many items so i don't need to write
(using <name>Context = new (... etc ...) ) { ... }
Repository eliminates initializing context for every operation, but don't dispose the context.
What is the best way to manage contexts? If i create other repository class and try to do any operation which will need objects from both contexts there is a problem.
Is there any other way or better way to implement repository, to manage contexts? Any interesting pattern?
A context is a unit of work, so you want one per web request.
Therefore, you should use constructor injection (i.e., a constructor argument) to supply a single context for all repositories, and dispose it at the end of the request.
Most DI frameworks will do this automatically.
Here is a nice post regarding the repository pattern on top of EF:
http://blogs.microsoft.co.il/blogs/gilf/archive/2010/01/20/using-repository-pattern-with-entity-framework.aspx
You might also check out posts regarding the Unit of Work pattern implementation:
http://blogs.microsoft.co.il/blogs/gilf/archive/2010/02/05/using-unit-of-work-pattern-with-entity-framework.aspx
http://devtalk.dk/2009/06/09/Entity+Framework+40+Beta+1+POCO+ObjectSet+Repository+And+UnitOfWork.aspx
Take a look at these blog posts as well:
http://initializecomponent.blogspot.com/2010/09/repository-like-facade-for-mocking.html
http://initializecomponent.blogspot.com/2010/09/repository-like-facade-for-mocking_12.html
Related
I know this is very close to opinionated question which is not tolerated in SO so I want to make it clear - I'm not asking what is the best alternative to Repository Pattern + UOW but what one could use instead.
I'm an Entity Framework enthusiast. Was introduced to .NET technologies about an year ago, when, DbContext and DbSet were already part of the Entity Framework so the discussion was already there, and I've read a lot about how the context is our generic repository and how the DbSet is our UOW and that nowadays if you have to consider using some sort of further abstraction it mostly benefits the ability to perform test and to ease the switching between different OR/Ms.
Well, it's probably true, but yet there are many articles about Repository pattern, do we really need it, what Entity Framework has become and so on, so I made the next step - if Repository pattern and UOW are not what used to be combined with the new versions of EF (5+) then what is the modern approach, what other options are now available to us to make better use of what Entity Framework offers out of the box? So, the problem is that literally I ended up with nothing in particular. Nothing remotely close to a tutorial or even a well described idea on how it is supposed to use EF now so this is the main reason to finally write a question here.
What I really like about Repository pattern and the way it works is the ability to keep things separated. By which I mean that I have seen people writing literally in every method that need say DB access something like:
using (var context = new MyDbContext())
{
Product prod = new Product();
prod.Name = "Something";
prod.Price = 10;
context.Products.Add(prod);
context.SaveChanges();
}
Obviously there is code that is repeated across the entire application and it seems natural to separate this in it's own method, project... Data Access Layer ... So this is the first thing that I find good about Repository pattern - it allows us to keep it DRY and that's always nice.
The second thing that I've always appreciated while using Repository pattern is when it comes to more specific queries that retrieve information that you should use from multiple methods. So for example if I need some method like : GetAllDataForUsersWithMoreThanTenPurchasesPerMonth() and having a repository it's pretty easy to write this method once and then just call it wherever it's needed, not to mention how much easier the maintenance is if you need to change something in this method and the business logic is only on one place and you don't have to go to each method and rewrite this specific piece of code.
So maybe there's much more that could be written about this but, that's something I have noticed in all application I've been working on so I'm really interested. What are the modern approaches? I'm talking mostly about small to medium applications.
There are dozens of variations around Repository + EF out there, so it's hard to tell what you're referring to as Repository Pattern + UOW. Maybe you could post one of your own Repositories so we can make suggestions ?
Many "no-repository" rants that have sprouted recently are really rants against Repository pattern misusage. Maybe the masses have been widely misusing it recently, that's why these people want to ban it - but they're wrong. There's nothing bad about Repository if you stick to what it was meant for originally - an object that seems like an in-memory collection to query from or add to, but maps to another layer under the covers. Understanding each pattern separately also helps. Repository != Unit of Work, and some repo implementations might not use a UoW at all.
If your code sample is supposed to show things that we could reuse in a base Repository implementation, it's probably a bad example and a bad idea. You don't want to force the scope of your Unit of Work into the limits of a single Add() or Delete() repository call. You want a higher-level, execution context-aware object to control the business transaction and thus the Unit of Work. It's not up to the Repo to decide if and when things are going to be flushed to the DB.
We have lots of repositories defined via the interface extends JpaRepository pattern. When running integration tests or certain entry points to our application, we only need a very small subset of those repositories.
Can we lazily load the actual repository implimentations?
Something equivalent to #Lazy on a #Bean? Note: I did at least attempt the naive solution of annotating the repository interface with #Lazy to no avail.
Even if it's a very old Question, I think some may still want to know about the use of #Lazy on Spring Data repositories :
it is actually supported since v1.5.0
Lazyloading will avoid to get all other dependency based on your main table or request. In your case you should set a limit / offset for that kind of operation.
From reading various books and articles, I seem to rather often find the usage of the Repository-pattern suggested. I get the point if you need to be able to swap out your data layer from one to another, but my question is, if I know with 100% certainty that I will not use any other tech for data access, is there any reason for using said pattern?
The thing that I find myself doubting the most is that I don't really see what this extra layer of abstraction can bring to the table in this scenario. From my experience, EF with its fluent linq-to-entities -functionality should be more than enough for pretty much all my needs.
The most usual cases seem to start the repositories with methods such as FindAll, Find, Add and Delete, all of which are very easily accessible directly through EF (so no code duplication to speak of).
So am I just missing some big point, or is the repository more for when you need to support multiple different data access technologies?
They are many opinions on the issue but after using repositories for 2 projects, i never tried it again.
Too much pain with hundreds of methods for all those cases with no clear benefits (i'm almost never going to swap out EF for another ORM).
The best advice would be to try it out so you can make an informed opinion on which route to take.
Some opinions against it here
I think you're on the right direction. I asked myself the same question two years ago after I've used the repository pattern in some projects. I came to the conclusion that hiding your ORM behind a repository implemented on top of your ORM will get you nothing but unnecessary work. In addition to implementing meaningless FindAll, Find, Add ... methods you would loose some performance optimization possibilities that the ORM gives you. Or at least it will get quite hard to apply some of those methods.
So if you're not going to switch your ORM within the lifetime of your project, I don't see any benefits in applying the repository pattern.
So instead of preparing for the situation where one could in future easily switch the ORM, I would suggest to do some more investigation upfront, wisely choose an ORM, stick with it and stay away from the repository pattern.
What people don't realize is that EF is already a Repository and a Unit-of-Work.
Repository has recently become an anti-pattern. Never use a design pattern because its cool or trendy or trying to build your resume, in fact this should be a standard rule for all design patterns.
Only build a Repository and Unit-of-Work on top of EF if your application is
very large (lasagna layer)
long-lived (10 years or so)
has more than 5 developers working in parallel
has developers that are separated geographically
requires a lot of maintenance
multiple data access infrastructures
A good indication is when upgrading from EF5 to EF6 requires you to knock on everybody's door.
I'm not as hot on the repository pattern as I used to be, but I still find it can be useful in the following scenarios (assuming swapping the ORM isn't one of them):
Unit testing (assuming you'd rather mock or stub than use Sqlite or hit a real db)
Being able to stub out data access during development via a repository that has an in-memory IEnumerable as its backing source.
I am actually in disagreement that EF is a correct example of a "Repository Pattern". It is a typed Data Access Layer and an exposed LINQ implementation.
Please note that if one fully endorses EF as "the business domain" then the above does not hold; however, I use EF - as poorly as it does - with Schema First, in which EF is not the strict business domain. The term "correct" is used to reinforce this viewpoint - adjust for your own perspective / design.
A correct Repository Pattern, in my book, exposes aggregate roots of relevant operations. That is, the implementation details (EF) is kept within the Repository, as much as possible. That is, the Repository takes care of the mapping of the relevant Domain objects to the underlying model.
This is an agreement with how Microsoft defines The Repository Pattern - note that the business entities are mapped to a data source. (And thus my fundamental disagreement with EF fulfilling this role: EF only has a chance of sanely maps business entities when designed from Code First.)
The best summation / article I have found is Repository pattern, done right by Gauffin. While he approaches the Repository pattern from a more extreme view than I, here are some key points as to why EF's simply bleeds through an Active Record / ORM pattern.
Here are some selected excerpts that highlight why I do not thing that EF is a proper implementation of a Repository Pattern.
The repository pattern is an abstraction. It’s purpose is to reduce complexity and make the rest of the code persistent ignorant. As a bonus it allows you to write unit tests instead of integration tests. The problem is that many developers fail to understand the patterns purpose - and create repositories [ie. EF] which leak persistence specific information up to the caller
..
Using repositories is not about being able to switch persistence technology (i.e. changing database or using a web service etc instead) .. Repository pattern do allow you to do that, but it’s not the main purpose.
..
When people talks about Repository pattern and unit tests they are not saying that the pattern allows you to use unit tests for the data access layer .. If you use ORM/LINQ in your business logic you can never be sure why the tests fail.
..
Do note that the repository pattern is only useful if you have POCOs which are mapped using code first. Otherwise you’ll just break the abstraction using the entities. [That is, only EF Code First can even attempt to meet this requirement.]
..
Building a correct repository implementation is very easy. In fact, you only have to follow a single rule: Do not add anything into the repository class until the very moment that you need it
And if you do use EF as a Repository - I believe it's still a typed DAL, as much as it bleeds - please do not try to hide it in a "more generic" pattern - a Repository pattern is not about type unification, it is about exposing aggregate roots for a particular context and operations on such.
See What specific issue does the repository pattern solve? as well.
While I speek against EF being a correct Repository Pattern - it is the Active Record pattern - I am not a Repository purist. That is there are cases when I will bleed EF (or L2S) entities in specific cases; I accept this as technical debt. Just understand the cost of breaking such a Repository / Domain boundary.
I have read almost all articles about Repository pattern and different implementations of it. Many of them judged bad practices (ex: using IQueryable<T> instead of IList<T>) etc. that why i'm still stuck and couldn't end-up to the right one.
So:
Do I need Repository pattern to apply IoC in my MVVM applications ?
If yes, What is the efficient IRepository implementation to EF Entities which is a good practice and better testable ?
How can I test my Repositories and UnitofWork behavior ? Unit tests against in memory Repositories ? Integration tests ?
Edit : According to answers I added the first question.
Ayende Rahien has a lot of posts about repository http://ayende.com/blog/search?q=repository and why it is bad when you are using ORM's. I thought Repository was the way to go. Maybe it was, in 2004. Not now. ORM's already implement repository. In case of EF it is IDbSet. And DbContext is UnitOfWork. Creating a repository to wrap EF or other ORM's adds a lot of unnecessary complexity.
Do integration testing of code that will interact with database.
The repository pattern adds an extra layer when you are using EF, so you should make sure that you need this extra level of indirection.
The original idea of the Repository pattern is to protect the layers above from the complexity of and knowing about the structure of the database. In many ways EF's ORM model protects the code from the physical implementation in the database so the need for a repository is less.
There are 2 basic alternatives:
Let the business layer talk directly to the EF model
Build a datalayer that implements the Repository pattern, this layers maps EF objects to POCO
For tests:
When we use EF directly we use a transaction scope with rollback, so that the tests do not change the data.
When we use the repository pattern we use Rhino Mocks to mock the repository
We use both approaches, Repository pattern gives a more clearly layered app and therefore maybe more control, using EF directly gives an app with less code and therefore faster to build.
Is it better to create and dispose a context in the repository class? or is it better to create the context in the service and pass it to each repository through dependency injection?
If it is only created in the repository, the methods cannot do lazy loading (no use returning IQueryable) in the service/business layer.
Most definitally create it outside the repository. If you create it inside the service the code is strongly coupled to the instance type of the context. This means that you cant have one of your repositories without also having EF. what you really want to do is layer your system so that a repository can use EF as the data source or possibly something else (such as an in memory table).
This matters a lot when it comes to unit testing as you dont want to have to instantiate your database in order to run a unit test.
Take a look at http://blog.staticvoid.co.nz/2011/10/staticvoid-repository-pattern-nuget.html which is my take on how a repository should be implemented with EF4, also i've created a nuget package to implement this pattern in such a way that the code to get a nicely decoupled repository system is about 4 lines.