DDD in C# with MongoDB Persistence — Part 2

Anup Marwadi
HyperTrends
Published in
2 min readJan 27, 2018

In the previous article, I introduced the Installment domain model to be used to calculate installments. In this article, I’m going to present the actual persistence strategies that can be used to persist this domain model in MongoDB.

Strategy 1- Using Serialization Attributes

The easiest way to add MongoDB persistence is by adding Serialization attributes. If you’re building your domain for a single project, I would recommend going with this approach as it gets you setup the fastest.

Simply add serialization attributes as shown:

Using this approach, one can easily persist this model to the Mongo database. A couple of important things to note:

  • BsonId attribute is mandatory when adding a record to the mongo collection. I’ve also exposed this as a parameter to the constructor instead of auto-generating it on the inside, because I want to reuse this model across different persistence mechanisms.
  • BsonRequired ensures that required fields have the necessary data before persistence.

That’s pretty much it! MongoDB makes it very easy to persist data.

Strategy 2 — Using External Mapping Files

One of the biggest drawbacks of adding inline attributes is that you really are tied down to the MongoDB as a persistence mechanism. If you, like me, run a Software Company, you’re going to end up packaging this into a Nuget package and use it across multiple projects. A customer may decide to persist to a SQL Database.

Instead of duplicating the domain model again, I’d rather that we make it persistence agnostic.

NOTE: Persistence Agnostic Domains are extremely hard to achieve. Especially as applications get extremely complex. I know a lot of people may argue otherwise, but experience has taught me otherwise.

So say all my Domains were in HyperTrends.Core.Domain library. I could easily build a new library called HyperTrends.Core.Domain.Mongo and reference the Domain library in it and then build Mongo Mappings. Likewise, I would build a HyperTrends.Core.Domain.SqlServer and add SQL Server mappings (using Entity Framework) there.

Here’s a quick example of how MongoDB mappings would look like in code:

Using this approach, the Domain model is completely independent of the underlying persistence mechanism. The InstallmentMap.Map() method can be called from your Startup.cs file so all mappings are taken care of when the application loads up.

Conclusion

There you go! Your MongoDB persistence using Domain models is complete. The domain however isn’t doing anything great yet. We’ll add some cool stuff to it in the next part in this series.

--

--

Anup Marwadi
HyperTrends

Tech Entrepreneur. Product Builder. Student for Life. CEO - HyperTrends, TicketBlox