Some days ago I read the post from codurance ncreasing complexity one entity at a time and on another discusion with @gulnor & Co about decoupling and ORM.
In both cases the ORM is used as a smell or antipattern. I can understand this opinion because I have read it on many other sources (Uncle Bob, etc.)
I just want to explain why we have chosen use an ORM and how we use it. We use it to decouple our system from a legacy database.
Our database is:
- really old and growing like a monster.
- in production and used by other system, so is not modifiable.
- has bad associations or not associations at all.
- bad designed so the tables are not related to domain entities.
So we need to use it but we don’t want to contaminate our system with the data base problems. What can we do to keep my persistence model aligned with our domain model but being able to store on our legacy DB? Our answer was use an ORM, in this case Entity Framework.
To be honest, our EF model is far away from our database estructure. We invest much time trying to get the entities we want from the tables we have.
Some transformations we made on our ORM:
– Associations that were not defined on the database are defined on the ORM.
– We merge two tables, that represent the same entity, on only one and use internal flags and procedures to keep the storing process on two tables.
– Use hierarchies on EF to split a table into two entities.
The good thing is that changing the ORM model is really easy, we can change a 1-N association to a N-M in seconds. Changing the names of a entity or property to align it to the domain model is trivial. We define what we need and use the ORM to transform the table structure on our entities.
Of course there are some limitations like remove an existing association on the database, but nothing is perfect, isn’t it? to be honest I would prefer that the association where defined on the ORM and not on the database, because the association could change over time and the ORM is easier to modify than the database.
For us, the ORM keeps us decoupled from our database that we can not change, but it helps us to dream in a future data base more aligned to our domain model. Maybe when our database was as we want it to be, the ORM is no longer needed, but this will be another history.