Recommended IRepository and IRepository<T> interface in C# - c#

I am looking for a simple IRepository interface for my mvc web application,
I have done a lot of searching around, and there are as many opinions as there are people.
So i decided to ask the experts
If you can recommend a IRepository and IRepository interfaces that are commonly used and answer the basic CRUD and query operations ( to support filtering ).
If you know of frameworks that also include implementations and can work with EF 4 I would love if you can mention them.
Thank you.
Edit:
As #Ladislav suggests what is the alternative, always just call linq to ADO.net calls from my code? Is it a good idea to use a POCO repository that abstract creation of custom POCOS from my business model, I have a Jewel POCO class that need to be parsed from varies DB entries, is this a common practice with legacy systems where I can't touch the DB architecture but only the presentation

Stop. Patterns should be used when they are needed - when they solve some common problem - not because they exist. You obviously don't need it at the moment because you didn't write any single requirement what the repository should solve for you - such requirements are crucial if you want to choose a "good one" to start with. Anyway a good one usually evolve during your development, it is most often not defined upfront.
Also generic repository with EF is one of the most stupid patterns I have ever used in my own project. It is good only to be parent of specific repository. It works only in basic scenarios where you most often don't need repository at all.
Something to read: What is the point of generic repository

The repository pattern is pretty straight-forward...you really don't need to use an existing framework. You can build the interface(s) yourself. There are a number of good examples out there in blogs of people building their own and also allows them to have near 100% code coverage in their tests. Here's a few examples (but they all follow similar patterns):
Using Repository Pattern with Entity Framework (Gil Fink)
100% UNIT TESTABLE LINQ TO SQL REPOSITORY (Kazi Manzur Rashid) -- I'm actually following some of his examples in my work
Working together: LINQ to SQL, IRepository, Unit Of Work and Dependency Injection (Stuart Harris)
And there are a ton more.
I think building it yourself, especially if you're just learning the pattern, will definitely teach you a ton about the pattern and also give you insight into what works for your situation and what doesn't.
I hope this helps! Good luck.

Related

Abstract repositories specific api under data model, and querying it using linq

at moment i'm working with few third party repository; these repositories allow me to access to datas only through some specific apis.
What i would to understand is if there is a pattern, that i should use, to abstract each api of each repository for mapping them under an unified datamodel; so that i can query datas using linq, regardless about underlying repository.
Ps :
I'm not interested in all crud operation i would only read queries results, i have no need to edit data (in any way).
Thanks in advance for help.
Your needs are a bit contradictory.
What i would to understand is if there is a pattern, that i should
use, to abstract each api of each repository for mapping them under an
unified datamodel;
Yes, take a look at Adapter, Facade and Bridge in a less degree (all of them are described in GoF). More general it relates to some unified contract (your Repositrory) and model translation. In such case I recommend to look at Anti-Corruption Level pattern from DDD, and also other DDD patterns related to model translation.
The point I confused with is
so that i can query datas using linq, regardless about underlying
repository.
Repository semantic is in hiding of technical details, thus you are working with Repository abstraction like In-memory collection. Actually, relying on ability of all Repository implementations to correctly translate and efficiently use your linq-like queries is a bit naive. Moreover it can be a sufficient limitation for separate (independent) evolution of your App and third-party-repositories.
Finally, as you are working with interface as with a public contract, all implicit technical or implementation logic assumptions (about how something is implementend in nutshell) lead to tight coupling with all consequences. But, if you still want to use LINQ, you can create wrappers for third-party repositories and implement your own LINQ-to-YourRepoTechs provider, but I think it's not worth to be done.
If your third-party repositories provide also technical-specific API, I would recommend to create autonomy service (Web) wrappers for them for 1) encapsulating of technical API difference, 2) translating model with respect to your needs. And to forget about LINQ.
It will be more robust and flexible.

Good Generic Repository Pattern when not Using Code First

I'm trying to wrap my head around repository pattern and dependency injection concepts for my ASP.NET MVC applications.
I ran across the article Repository Pattern with Entity Framework, and really liked how simple the code is. There doesn't appear to be that much code and it's all completely generic. That is, there's no need for multiple repositories for the different objects in the database as most people appear to be doing. This is just what I want.
However, the code is written for code first, which I'm not planning to use.
Questions:
Is there a good reason why the same code couldn't be used for applications that don't use code first?
Can someone recommend a better approach for my applications that don't use code first? (Keeping in mind that I'm absolutely sold on this generic pattern.)
Any other tips to help me move forward?
You can make a repository interface for any underlying data store. You can simply define an interface like so:
public interface IRepository
{
IQueryable<T> GetQueryable<T>();
void Insert<T>(T item);
}
Then, you can implement a class behind this which will implement it. It doesn't have to be code-first; you can back it with an ObjectContext created from an EDMX file, for example.
The key here is in creating the right abstraction. You can easily do that with an interface, and then implement it however you want behind the scenes.
Because you're using dependency injection, the implementation doesn't matter as much, as long as you've defined the contract correctly, the implementation (and testing of it) should be simple. And if it doesn't work, or you want a different data store altogether, you just tell your dependency injector to use a different implementation, the contract doesn't change.
The same can be said for any abstraction you create; you can have an interface that reads and writes data (like the article you reference does), you just have to pull the abstraction out.
Have a look on this. I think this link will help you most
http://www.codeproject.com/Tips/572761/Generic-repository-pattern-using-EF-with-Dependenc
In this link Generic repository pattern is used with dependency injection in MVC project without using code first approach.

Repository: Examples for a Decorator / Repository pattern in C#

I had the wrong idea of how to create a repository. I created a single repository for each Entity that would CRUD using an ORM, which worked very well. However, I needed more and didn't know how to do it without messing up my existing code.
I wanted to add filtering based on Logins. I eventually found Castle.Windsor references showing something like this:
var ControllerContactRepo = new SecurityContactRepo( new ContactRepo() );
Where the Controller in MVC accesses one repository for Contacts which handles both CRUD and security without the controller knowing it. I presume the POCOs passed between repositories change based on the Liskov substitution principle, and the repositories are done with the decorator design pattern?
Where can I see some C# examples of this technique before I jump head first in to Castle Windsor? I am familiar with Constructor based IoC but not so much DI. I really want to know the nuts and bolts of this technique before I abstract it away with Windsor.
Links to website tutorials would be great, or book suggestions.
Here is a good article for you http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/

Is the DAO Pattern Widely Used in .NET?

Is the DAO—Data Access Object—a commonly used pattern in .NET? I've always used DAOs as a way to provide access to my data layer. For example I might have a thin interface over my EntityFramework ObjectContext exposing all of my ObjectSets as IObjectSet.
Complex queries would then be exposed by DAOs, each of which with a dependency on this interface. I might have a ProductDAO that exposes methods like GetProductsOnSale() or GetInfrequenlySoldProducts(). My controllers or presenters would then use these methods, which would likely be virtual to allow stubbing specific results for unit tests.
So is this a commonly used idiom in .NET? For some reason the overwhelming majority of examples I see online using this pattern are based on Java. Even this question on DAO best practices is tagged as Java and not C#.
There's nothing wrong with using something from another community, I just have a slight fear that everyone around me is doing things differently...
It is a common idiom in .NET. I have used it and have seen it used in many places.
It is built into the framework - see the System.Data namespace - many of the classes are base classes for specialized providers (SQL Server, Oracle, MySQL etc...) and operations are executed on the base classes.
However, what you are describing sounds more like the Repository Pattern to me, not simply the use of Data Access Objects.
This is also used in many projects, though is not built into the framework.
I use the DAO pattern extensively.
You mentioned the Entity Framework; to that I would add that I find DAO much better than DataSets and DataTables, which are too much like a database an not enough like an object for my tastes. For example, DataRows can't be added to more than one data table, so I can't pass around subsets of the loaded data to different objects without moving them to a container that wasn't built to contain them. (I.e., it seems like a DataRow should be in a DataTable, but they can only be in one DataTable at a time.) DataRowViews are clunky and not nearly as intuitive as adding entity objects to another list.
My biggest recommendation on the usage of the Repository pattern for encapsulating data access (which indeed is a very good pattern), is to be able to create a generic repository. But to create a very smart generic repository that gives you basically live wiring to immediate access to all standard CRUD operations, along with access to the complex query construct that you won't expose past you ISomeService facade.
The most important thing about using a generic repository, is you want it to be based on constructor injection and not based on inheritance. This way you can compose your SomeService to be dependent on many generic repositories that it would need to fulfill a meaningful business domain boundary.
I wrote an indepth blog on this concept. Creating a common generic and extensible NHiberate Repository version 2. While this blog post is specific in reference of NHibernate you can take the same core concepts and apply them to almost any DAO.
Note with some tools, like Entity Framework, Linq2Sql and RavenDB to name a few, they expose very refined repositories themselves and might not necessarily benefit from adding an additional wrapper.

A repository, according to the Repository pattern, should provide queries or actual entities?

I am currently refactoring my code for a web application developed using ASP.NET MVC3 with C# and Razor. One of the pattern I am using in order to better structure my application is the Repository pattern, which, besides being a really useful pattern, is also a frequent matter of discussion within the developers' community.
In this context I found an article by Fredrik Normen which states that, according to the definition of Repository,a repository class must provide actual entities (for instance List in .NET) and not queriable objects (IQueriable in .NET). Instead in the NerdDinner tutorial from ASP.NET MVC official website they use IQueriable when the Repository has to provide multiple instances of the same object and the actual entity when the repository has to provide a single instance of the object.
What is the most correct approach to use when modeling a repository class/interface according to the Repository pattern?
Thanks
Francesco
In my opinion this sort of thing is detrimental to the use of your time. ;-)
In theory, your repository should return objects or traditional collections of them, yes. However, even the definition of the repository pattern you link to uses the term "collection-like interface". Certainly, an IQueryable<Entity> is a 'collection-like' interface, yes?
In practice, I almost never think about the distinction... but I always try to put all of the querying code in the repository. I'd say 90% of my collection-based repository methods return traditional collections, while the other 10% return something based on IQueryable<>. The exceptions usually have to do with paging; so I can get the totals from the query down the line if needed, and not have to get that info early if I don't need it. It's a little lazy, but it works for me.
But I do think it's a good idea to always try to return traditional collections, because that will mean you are encapsulating all of your querying in the repository, which is where it should be. I would recommend just not to get too caught up in the extreme levels of adhering to someone's idea of what the requirement is for pattern-X
Opinions will differ on that, as you've already found. For small scale applications it's probably OK to let your repositories expose IQueryable.
One thing that you certainly should not do is pass IQueryable to your views. Make sure your views receive only materialized objects and collections (like List or arrays).
This way if an error exists in a query somewhere, it will occur in the controller (or repository) and not in your view. This enables you to test the queries and handle errors gracefully.

Categories

Resources