Advice on mapping of entities to domain objects

mstrand picture mstrand · Nov 15, 2013 · Viewed 26k times · Source

I'm currently working in a project where we are starting to build an application using a DDD approach. We are now looking into using Entity Framework 6 code first to help us with data persistence. My question is how to best handle data mapping between our domain objects and EF entities?

Answer

MikeSW picture MikeSW · Nov 18, 2013

To keep your app and yourself sane on the long term, NEVER EVER start your DDD app with persistence related issues (what db, what orm etc) and ALWAYS (yes, always) touch the db as the last stage of the development.

Model your Domain and in fact any other model except persistence. Use the Repository pattern to keep the app decoupled from the Persistence. Define the repo interface as needed by the app and not tied to the db access method (that's why you're implementing the persistence later so you won't get tempted to couple your app to persistence details).

Write in-memory implementations for the repo interfaces, this usually means a simple wrapper over a list or dictionary so it's VERY fast to write and more importantly trivial to change. Use those to actually test and develop the app.

After the interfaces are stable and the app works then it's time to write the persistence implementation where you can use whatever you wish. In your case EF and there it comes the mapping.

Now, this is highly subjective there isn't a right or wrong way, there's the way YOU prefer doing things.

Personally, I have the habit of using mementos so I get the memento from the domain object and then manually mapping it to the (micro)ORM entities. The reason I'm doing it manually is because my mementos contain value objects. If I would be using AutoMapper I'd be needing to confingure it and in essence I'd be writing more code than doing it manually

Update (2015)

These days I just Json the object and either use a specific read model or store it directly in a read model with a Data column that contains the serialized object. I use Mementos only for very specific cases. < /update>

Depending on how your domain objects look and how the EF entities look you might get away with using automapper for the majority of the mapping. You will have a harder time testing your repositories though.

It's up to you how you do it, find the way it suits your style and it's easily maintainable but NEVER EVER design or modify your domain objects to be more compatible or to match the ORM entities. It's not about changing databases or ORMs, it's about having the Domain (and the rest of the app) properly decoupled from the Persistence details (which the ORM is).

So resist the temptation to reuse things which are other layers' implementation details. The reason the application is structured in layers is because you want decoupling. Keep it that way.