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:
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
ObjectContextcreated 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.