To ORM or not to ORM

Recently I’ve heard comments that developers want to simplify and remove abstractions, and ORM (object-relational mapper) is one of them. Having an ORM, usually Entity Framework in .NET, has been pretty much standard for years. But is this good or bad?

ORM is a tool, and as with any tool, you should think and reason why are you using that tool. Saying “because we’ve always done so” is a bad reason. There might be legitimate reasons for keeping ORM, but if not, then it’s unnecessary or even harmful, and should be removed. So what are the possible reasons for using ORM?

I can identify 3 possible reasons:

  1. Database abstraction
  2. Composing queries
  3. Amount of code

Most commonly people mention abstracting the database. It’s just a repository for objects. When using ORM, you don’t “need” to know even that the database exists. Of course, we know that’s not totally true, and often ignoring the database underneath causes problems with performance and query translation. Maybe you wanted only a subset of objects, but the database is returning unfiltered list of all objects and doing it in memory. Or it’s joining too many tables. So it’s legitimate to say that hiding the real underlying database is not always a good thing. Ok, we have decided that for performance and visibility reasons we don’t want to abstract away the database. Is ORM unnecessary now? Maybe, maybe not.

Actually, my favorite reason for using ORM is being able to compose queries. Let’s say you’re querying sales orders. Sometimes you want orders for a specific user. Sometimes you only want open orders. You have 2 options. You can hardcode multiple queries or you can compose the queries from multiple filters. Hardcoded queries makes sense when there’s not too many combinations, or it’s possible to do additional filtering client side (after the database query). But sometimes the number of possible query combinations explodes and you need to compose. You can compose SQL strings by catenation, but from my personal experience, that’s a horrible idea, leading to many hard to fix bugs. SQL is simply not made to be manually composed. Meanwhile, Entity Framework makes composing queries safely much easier. Personally, if I need composed queries, I would use EF over raw SQL. Of course, this depends on the application.

Third, you can argue that using an ORM increases or decreases the amount of code needed. Again, this depends on the application and how you’re using the ORM. Can you reuse entities for different queries? Are you making use of lazy loading? Is lazy loading a good idea to begin with? It may be a reason for using ORM or against it.

Leave a Reply