Getting Started with Marten

Getting Started with Marten

by 

| November 23, 2021 | in

As I wrote in my previous blog post, PostgreSQL is a very capable SQL database. But one thing very interesting about PostgreSQL is its excellent support for JSON documents.

The ability to store JSON documents in a database basically allows the database to run like a NoSQL document store, effectively combining relational and non-relational into one persistence option.

Combining NoSQL and SQL into the same persistence store is a common goal. The reason is we often need to store both types of data. We often have a lot of very rigid data that fits great into a SQL option, but we often have some data that is too variable to store in a SQL or relational structure.

I have worked on teams where we have created crazy DB structures to handle the storing of data that didn’t fit well into a relational structure.

Storing that non-relational data into a JSON or an XML column makes a lot of sense; many of us have tried to do it. Unfortunately, the tooling around doing this isn’t great, and it will almost require you to write a lot of wrapper code to make this option livable.

In walked Marten. Marten is a .NET library that uses PostgreSQL’s JSON column to extend the abilities of PostgreSQL to be both a document and a relational store. Marten solves the tooling problem I mentioned above.

Here’s how to get started with Marten.

Install the NuGet package.

dotnet add package Marten --version 4.1.0
dotnet add package Marten.AspNetCore --version 4.1.0

Now we need to configure Marten.

Now that we have Marten in place, we can start using our PostgreSQL DB as a NoSQL store.

To save a contact into the database, we could do so with the following code.

To retrieve a list of contacts.

The code to interact with Marten is very simple. They have done a great job making a simple interface that will feel very natural for C# developers.

How does Marten store data? It puts your data in a data column, and the type of data is stored in the mt_dotnet_type column.

How Marten stores data

Marten is pretty amazing. It gives us the ability to store documents in our database, but it doesn’t feel like some sort of bad hack. I recommend you give it a try.


Related posts