This is my last post on my series on ORMs. Even after all of the arguments against an ORM, everyone wants to use them. It seems like there are always two reasons for this: 1)the lure of keeping developers from learning SQL is just too great 2)the belief that the issues with ORM tools won't happen to me. In every company I've been involved with, when an ORM was proposed, it was eventually implemented regardless of my protests. So, there are a few things that you can do to mitigate some of the pain that you may eventually face.
Know When Not to Use the ORM
ORMs really are great for CRUD operations where your data tables correspond directly to the tables in your database. In those cases, the ORM saves you from writing INSERT, UPDATE, and DELETE statements directly. But in cases where there is an impedance mismatch between the object model and data model, you should consider immediately using stored procedures.
Also, for basic entity navigation activities an ORM can be a big time-saver. But if your developers are beginning to ask questions about how to write complex queries in your ORM's query language, you need to again quickly step back and consider using a stored procedure instead.
If your ORM can only return objects but you have a bunch of queries that return discrete data values, then don't use the ORM. Otherwise you risk "object-bloat" and poor performance. You should be able to return raw data from aggregations for instance. If you can't, don't use the ORM in those situations.
The theme here is that I feel you should use your ORM whenever it can make your life easier without affecting performance adversely. When it begins to become a hindrance, or when you can foresee it doing so, then fallback to stored procedures or other data access methods.
The ORM Should Be Behind Interfaces
Never call ORM methods directly. Use a wrapper. There are plenty of reasons to do this. A few:
- It's just a good coding Best Practice.
- It will help you be less tightly-coupled to your ORM vendor.
- You may need to add some extra logic in the future that your ORM can't handle. Complex validation comes to mind. This is kinda like implementing a database trigger at the ORM layer.
- You wish to limit features of your ORM that are available but you have deemed "off limits" to your staff. Limiting the use of direct SQL is an example.
Understand Your ORM and How It Uses Metadata
Some ORMs get column-level metadata at runtime. It's doubtful that your running system's column-level metadata will change very frequently, so why is this being generated at runtime. It should be generated at design time. ORMs usually use reflection to do this, which further adds insult to injury.
Some Other Points:
- Application Logic and Business Objects Should Not be Dependent on the ORM
- If you follow MVC development principles, then do not use the ORM on the controller.
data architecture orm