When to use repository pattern

design-patternsormrepository

I have read recently that it is not good practice to use the repository pattern in conjunction with an ORM. From my understanding this is because the abstraction they provide over the SQL database is too leaky to be contained by the pattern.

I have a couple of questions about this:

  1. What do you do if you want to switch out ORMs? You would have ORM specific code in your application if you do not contain it in a repository.

  2. Is the repository pattern still valid when not using an ORM and you are using ADO.NET for data access and populating object data yourself?

  3. If you use an ORM but not the repository pattern where do you keep commonly used queries? Would it be wise to represent each query as a class and have some sort of query factory to create instances?

Best Answer

1)True, but how frequently do you switch out an ORM?
2)I would say so, because an ORM context is sort of a repository and hides a lot of work involving creating queries, retrieving data, mapping, etc. If you don't use an ORM, that logic still has to reside somewhere. I don't know if that would qualify as the repository pattern in the strictest sense of the word though...
3)Encapsulating queries is something I see frequently, but that's usually more for testing/stubbing purposes. Other than that, I would be careful when reusing a query across different parts of an application, because then you risk creating a dependency on something which could change n-times (n being the number of places where you use the query).