IRepository - Entity implementation - repository-pattern

I'm using Repository and UnitOfWork pattern in order to mantain decoupled code and to achieve a simple way to test my application.
The inner implementation use EntityFramerowk with DB first and all works fine.
Tomorrow, I might want use some other concrete repository implementation such as file system rather than database, so some repository method like Find, or Delete could be difficult to accomplish, because my entities doesn't implement anything about primary-foreing keys and so on. It implies my entity research on repository should looks for all fields matching with T object parameter.
So, is it good practice enforce my entities for some interface implementation? For instance:
Is there some available example or tutorial about this?

some repository method like Find, or Delete could be difficult to accomplish, because my entities doesn't implement anything about primary-foreing keys and so on. It implies my entity research on repository should looks for all fields matching with T object parameter.
That's how NOT to implement the repository. A repository interface (contract) should be ignorant of the underlying implementation details such as Entity Framework. Only this way you can have a different implementation of the repository and achieve seaparation of concerns. Also, testing code that uses the repository should not involve EF or db at all.

Related

Few things about Repository Pattern that I simply don't understand

I've read quite a few topic on what Repository is, but there are still few things bugging me.
To my understanding only difference between Repository and traditional data access layers are Repository's query construction capabilities ( ie Query Object pattern). But when reading the following definitions of a Repository Pattern, it seems we can still have Repository even if we don't implement Query Object pattern:
a)
From:
Repositories are the single point where we hand off and fetch objects.
It is also the boundary where communication with the storage starts
and ends.
I think above quote suggests that Repository is an entry point into DAL. In other words, according to the quote, the DAL consumer (say Service layer) comunicates with DAL via Repository. But shouldn't instead data context represent an entry point into DAL ( thus Repository should reside within data context )?
b)
From:
The primary thing that differentiates a Repository from a traditional
data access layer is that it is to all intents and purposes a
Collection semantic – just like IList in .Net
Don't most traditional DALs also have methods that return a collection (for example List<Customer> GetAllCustomers())? So how exactly is a collection-like semantic of a Repository any different from collection-like semantic of a traditional DAL?
c)
From:
In a nutshell, the Repository pattern means abstracting the
persistence layer, masking it as a collection. This way the
application doesn't care about databases and other persistence
details, it only deals with the abstraction (which usually is coded as
an interface).
As far as I know, the above definition isn't any different from the definition of a traditional DAL.
Thus, if Repository implementation only performed two functions – having the collection-like semantics and isolating the domain objects from details of the database access code – how would it be any different from a traditional DAL? In other words, would/should it still be called Repository?
d)
What makes the following interface a Repository interface instead of just a regular DAL interface?
From:
public interface IPostsRepository
{
void Save(Post mypost);
Post Get(int id);
PaginatedResult<Post> List(int skip,int pageSize);
PaginatedResult<Post> SearchByTitle(string title,int skip,int pageSize);
}
Thank you
FYI I asked a very similar question over here and got some excellent answers.
The bottom line is it appears to depend on the complexity of your architecture. The repository pattern is most useful to create a layer of abstraction when you need to access different types of data stores, i.e. some data is in entity framework, some is on the file system, etc. In simpler web apps with a (probably unchanging) single data store (i.e. all data in SQL Server, or Oracle, etc) it is less important. At that point something like the Entity Framework context object functions as a repository for your entity objects.

Implement a fake NHibernate repository

I am using StoryQ to perform some basic integration testing and we are using NHibernate as our ORM.
When I started, I didn't know that NHibernate implemented the Repository pattern and so I created my own IRepository in order to run my integration tests.
However, considering that NHibernate already implements the Repository pattern, I assume that it is doing so against some kind of interface. So, I would like to work against NHibernate's interface for the Repository if my assumptions are correct.
I have tried to search for it but I come across information that to do that I need to work against the ISession interface. As I do not really know NHibernate that well, can someone explain why I would need to implement my fake repository against the ISession interface? What is the IRepository equivalent in NHibernate? Is there some tutorial which goes into greater depth into the matter?
NHibernate doesn't implement the Repository pattern. It replaces it.
SQLite in-memory databases are nice if you've got a simple database implementation, but I've found that things can become cumbersome quickly, almost to a point where it becomes as painful, if not more, to use SQLite as it is to stub/mock ISession/ICriteria/etc.
One perfect example of this: In one of my recent projects, in which I was using PostgreSQL as my production database and SQLite as my test database, I had a need to extend NHibernate to add support for an aggregate function that was recently added to PostgreSQL. Figuring out how to add this was a story in itself, but I worked it out. I then had to find a functional equivalent in SQLite. I needed an aggregate function that worked in the same exact way as its Postgres counterpart. There was none. I asked around and was told that there were ways to extend NHibernate to "fake" this function in SQLite. I also had the option of extending SQLite to add this functionality.
All I wanted to do was write two, maybe three, tests around the scenario that I was trying to implement. I ended up spending way too much time trying to ensure functional equivalency between the two systems. It wasn't worth all this effort for one function. And what would happen if down the road, I needed to add another function?
I think SQLite is useful. It's a great lightweight database system and I love that you can conveniently use it as a in-memory database for simple scenarios. However, I'm not sure it's worth using beyond that. I think from now on, I'll be using the same database across all environments, even if it means having slower integration tests for all data persistence logic.
I'm not sure where in core NHibernate there is an IRepository interface (AFAIK there's none) so you might be referring some other NHibernate side projects.
It is not the best approach to go about mocking ISession either. The best thing in my opinion, is to use a real in-memory database that is fully supported by NHibernate. You may need to check how to configure NHibernate to run on sqlite in-memory database, which basically is just configuring NHibernate in your tests.
The good thing about this approach, is that tests run with a very good speed, as if there's no database involved, and you don't need to abstract away all your ORM functionality (and loose features too) just to run / drive your tests.
The approach I've taken is to implement an IRepository and GenericRepository, to wrap the ISession Save and Delete methods. Also, GenericRepository also implements IQueryable using NHibernate's LINQ provider. My implementation borrows heavily from Javier Lozano's MVC Trubine project. His implementation is here: https://github.com/jglozano/mvcturbine/blob/master/src/Blades/NHibernate/MvcTurbine.NHibernate/GenericRepository.cs
This works for about 80% of the queries I need. For the rest, I create a Query Object to wrap the query. That way, I can use ICriteria, IQuery, IQueryOver or LINQ, whichever the needs of the query dictate. Fabio Maulo explains it pretty well here: http://fabiomaulo.blogspot.com/2010/07/enhanced-query-object.html
Both approaches allow easily mocking away the dependency.

Generic Repository With EF 4.1 what is the point

As i dig deeper in to the DbContext, DbSet and associated interfaces, I am wondering why you would need to implement a separate "Generic" Repository around these implementations?
It looks like DbContext and IDbSet do everything you need and include the "Unit Of Work" inside DbContext.
Am I missing something here or does it seem people enjoy adding another layer of dependency for no reason.
You are actually right. DbContext is an implementation of the unit of work pattern and IDbSet is an implementation of the repository pattern.
Repositories are currently very popular and overused. Everybody use them just because there are dozens of articles about creating repository for entity framework but nobody actually describes challenges related to this decision.
Main reasons for using repository are usually:
Hide EF from upper layer
Make code better testable
The first reason is some kind of architectonic purity and great idea that if you make your upper layers independent on EF you can later on switch to other persistence framework. How many times did you see such thing in the real world? This reason makes working with EF much harder because your repository must expose a lot of additional features wrapping what EF allows by default.
In the same time wrapping EF code can keep your code better organized and following Separation of concern rule. For me this can be the only real advantage of repository and unit of work but you have to understand that following this rule with EF will maybe make your code better maintainable and better readable but in the initial effort to create your application will be much higher and for smaller applications this can be unnecessary complexity.
The second reason is partially correct. The big disadvantage of EF is rigid architecture which can be hardly mocked so if you want to unit test upper layer you must wrap EF somehow to allow mocking its implementation. But this has many other consequences which I described here.
I follow Ayende's blog. If you ever used NHibernate you probably know his articles. This guy recently wrote several articles against using repository with NHibernate but NHibernate is much better mockable.
I am struggling with the same issues, and mockability for unit testing of the EF layers is important. But I ran across this great article which explains how to set up the EF 4.1 DbContext to be mockable by making sure your derived DbContext implemented a generic interface and exposes IDbSet rather than DbSet's. Since I am using a Database First approach, because our database already exists, I simply modified the T4 templates used to generate my derived DbContext to generate it to return IDbSet interfaces, as well as derive from my generic interface. That way the entire thing can be easily mocked, and you don't need to implement your own Unit Of Work or repository pattern. Just write your service code to consume your generic interface, and when you go to unit test it, just mock the generic interface with specific test data and you are good to go.
http://refactorthis.wordpress.com/2011/05/31/mock-faking-dbcontext-in-entity-framework-4-1-with-a-generic-repository/
One reason for creating the repository is so you can hide the implementation of DBSet and DbContext if you decide to move from EntityFramework to something else or vice versa.
For example, I was using NHibernate and I wrapped all of the calls to that framework inside my repository classes. They return IEnumerable for their gets to be "generic" and my repositories have the standard CRUD operations (update, delete, etc). I have long since moved to Entity Framework. Upon doing so, I did not need to change anything in my ViewModel classes or beyond because they pointed to my repository--I only needed to change the inside of my repository. This made life much easier when migrating.
(I used NHibernate because we are connecting to the ISeries, and at the time, there were no cost affective implementations using EF with the ISeries. The only one available was to pay $12,000 to IBM for their DB2Connect)

Is that normal Unit testing takes all the behavior out of my classes?

I'm starting a new project and I want to use unit testing.
So I wrote my services classes which are implementing interface and waiting for interface in their parameters so I can easily mock these classes.
My question: there is absolutely no code in my business class! (like Customer)
Is it normal? is it normal even without unit test ? what kind of code would you put in a class like "Customer"?
No, it doesn't sound normal to me - unless you are at the very beginning of your project and Customer is as yet just a skeleton, and you know it will get more functionality over time.
Otherwise it may be a sign of a design issue, such as an anemic domain model.
It is not the unit tests' fault. Unit tests don't in any way enforce one to create dumb classes without real functionality.
I don't know if normal is the right word here, I'd rather say that the situation you have found yourself in is very common.
I see this happen most often with people starting in on Domain Driven Design and also when people use design patterns such as MVVM - all the logic falls into services and controllers and managers (which are themself a smell IMO), and the core domain model becomes a very anaemic set of DTOs.
What I would suggest is returning to your object modelling and looking at your services and seeing where you have removed logic from your Customer object which is actually a core concern of the customer. That is - what does the customer object do? Some of this will belong in external services, but there will also be key processes which are the domain of the customer.
When you design clearly, there might be the case, where some classes are just aggregates of Data. This is part of the MVC Pattern, where the models should not contain much logic. However if you do have absolutely no code in your classes there is something seriously wrong.
To me it sounds, like you are trying some kind of dependency injection, but you are not only injecting the dependencies, but rather everything. This is taking the pattern to far, so it might be becoming it's own anti-pattern.

Why does ObjectContext class not derive from some Interface?

I consider folks at MS way more smarter than I am. I was trying to build/test a repository which almost follows this approach except that I want to loosely couple the ObjectContext dependency inside the repository. I found out that in order to do decouple this I need to jump a lot of hoops as shown in this article.Even this approach is difficult to work with when
You have an edmx from an existing database
You have a generic repository built around the ObjectContext interface and IObjectSet
While unit testing you want to fake out this object context and keep all the operations in memory. Think testing Repositories.
Now the real question, why did the creators of ObjectContext decide not to have IObjectContext ?
I hope my question makes sense, I will be glad if someone can prove that it doesnt and shows me the way.
Thanks in advance!
Since the context is a partial class, you can easily add an interface to it in a separate file:
public partial class YourContext : IMyCustomInterface, and you can put in IMyCustomInterface any signatures you want to use from the generated ObjectContext.
Or you could go about the (generally) more recommended way, which is to abstract further than the ObjectContext into Repositories like in this blog post(that entire series of posts is interesting and relevant) or this one.