Jonathan Wood
Jonathan Wood

Reputation: 67193

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:

  1. Is there a good reason why the same code couldn't be used for applications that don't use code first?
  2. 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.)
  3. Any other tips to help me move forward?

Upvotes: 2

Views: 1019

Answers (2)

vijay
vijay

Reputation: 1353

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.

Upvotes: 1

casperOne
casperOne

Reputation: 74530

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.

Upvotes: 3

Related Questions