Search code examples
c#ormrepositoryabstraction

Why abstract an ORM?


I often see code that uses the repository pattern to abstract the ORM. Why is this done? Isn't the ORM already an abstraction and acts as a repository itself?

Is there a big difference between

public class EmployeeRepo 
{
    GetById(int id) { //Access ORM here };
}

Consuming data:

public class MyController{
    private EmployeeRepo = _Repo = new EmployeeRepo();

    public ActionResult ShowEmployee(int id)
    {
        var emp = _Repo.GetById(id);
        //Versus
        var emp = ORM.Where(e => e.Id == id);

        return View(emp);
    }
}

Why should I go through the work of recreating what the ORM is already giving me?


Solution

  • I often see code that uses the repository pattern to abstract the ORM.

    That's not needed in 99.(9)% of projects. Programmers seems to be over the moon by the fact they can create yet another abstraction over abstraction.

    Why should I go through the work of recreating what the ORM is already giving me?

    You should not do that, in fact, you create more problems, to name a few:

    • Has customer explicitly requested the feature to switch easily between ORMs? Really? Have you got a budget for this?
    • You ready to introduce test coverage for your abstraction, you have time and money for this
    • Have you got logging framework in place?
    • Have you consider design time to figure out common API that you can support? What about caching, sharding, load distribution, stored procedures, triggers?
    • Are you prepared to spend time to upgrade to a new version for several ORMs, are you ready to fix breaking changes?

    What is better, is to use interfaces/base classes from the ORM itself, thus you can test and mock it easily.