Practical ASP.NET

Enforce Referential Integrity Between Documents in Marten

Marten is PostgreSQL-based, sotake advantage of relational features where it makes sense. Here's an example.

Marten is an open source .NET document database library that allows the storage, loading, updating and deleting of objects as documents in an underlying PostgreSQL database.

Even though Marten stores .NET objects as JSON documents, because Marten is built on top of PostgreSQL (which is a relational database), it can take advantage of relational features where they make sense.

Suppose you have a role-playing game that has the classes as shown in Listing 1. In the Player class there's a reference to the Kingdom in which the player was born. This int should refer to a Kingdom document in the underlying document store.

Listing 1: Document Classes
class Player
{
  public int Id { get; set; }
  public string Name { get; set; }
  public int BirthKingdom { get; set; }
}

class Kingdom
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string History { get; set; }
}

If you make use of the classes from Listing 1 to insert a new Player, even if the BirthKingdom is non-existent, there will be no error on insert. Listing 2 shows code to insert a new Player document.

Listing 2: Inserting a Player with an Invalid Kingdom Reference
DocumentStore store =
  DocumentStore.For(
    "host = localhost; database = RPGDatabase; password = g7qo84nck22i; 
    username = postgres");


using (IDocumentSession session = store.LightweightSession())
{
  Player newPlayer = new Player
  {
    Name = "Krondure",
    BirthKingdom = 123456 // non-existent Kingdom document
  };

  // Add the object to the session
  session.Store(newPlayer);

  // Update database
  session.SaveChanges(); // No error
}

Executing the code in Listing 2 results in the new Player document being stored without error.

Using Marten, it's possible to enforce the referential integrity between the Player and Kingdom. There are two methods to accomplish this.

Configuring Referential Integrity with Attributes
The first method is to decorate the relevant property with the Marten [ForeignKey] attribute. In the case of the Player class, this attribute would be applied to the BirthKingdom property and as a parameter to the attribute, the target document type is specified as shown in here:

{
  public int Id { get; set; }
  public string Name { get; set; }

  [ForeignKey(typeof(Kingdom))]
  public int BirthKingdom { get; set; }
}

Now, trying to insert a new Player with a non-existent Kingdom will result in an exception: insert or update on table mt_doc_player violates foreign key constraint mt_doc_player_birth_kingdom_fkey.

Configuring Referential Integrity with Document Stores
As an alternative to using the Marten [ForeignKey] attribute, the foreign key relationship can be configured at the document store level as shown here:

DocumentStore store =
  DocumentStore.For(configure =>
  {
    configure.Connection(
      "host = localhost; database = RPGDatabase; password = g7qo84nck22i; us
       ername = postgres");

    configure.Schema.For<Player>().ForeignKey<Kingdom>(on => on.BirthKingdom);
  });

Once again this will cause the aforementioned exception to be thrown when the Kingdom does not exist.

Inserting Document with Referential Integrity
To prevent the exception from being thrown, the BirthKingdom set in the new Player must refer to an existing Kingdom document Id. Notice in Listing 3 that it's possible to create both a new Kingdom and Player at the same time.

Listing 3: Inserting Related Documents
using (IDocumentSession session = store.LightweightSession())
{
  Kingdom newKingdom = new Kingdom
  {
    Name = "Island of Hrothdo're",
    History = "An island of mystery...."
  };

  session.Store(newKingdom);

  Player newPlayer = new Player
  {
    Name = "Krondure",
    BirthKingdom = newKingdom.Id
  };

  session.Store(newPlayer);

  // Update database
  session.SaveChanges();
}

When SaveChanges is called, Marten will insert the dependent document first -- the Kingdom document in this case -- before inserting the Player document.

To learn more about Marten, check out the Marten Documentation page.

About the Author

Jason Roberts is a Microsoft C# MVP with over 15 years experience. He writes a blog at http://dontcodetired.com, has produced numerous Pluralsight courses, and can be found on Twitter as @robertsjason.

comments powered by Disqus

Featured

  • What's Next for ASP.NET Core and Blazor

    Since its inception as an intriguing experiment in leveraging WebAssembly to enable dynamic web development with C#, Blazor has evolved into a mature, fully featured framework. Integral to the ASP.NET Core ecosystem, Blazor offers developers a unique combination of server-side rendering and rich client-side interactivity.

  • Nearest Centroid Classification for Numeric Data Using C#

    Here's a complete end-to-end demo of what Dr. James McCaffrey of Microsoft Research says is arguably the simplest possible classification technique.

  • .NET MAUI in VS Code Goes GA

    Visual Studio Code's .NET MAUI workload, which evolves the former Xamarin.Forms mobile-centric framework by adding support for creating desktop applications, has reached general availability.

  • Visual Studio Devs Quick to Sound Off on Automatic Updates: 'Please No'

    A five-year-old Visual Studio feature request for automatic IDE updates is finally getting enacted by Microsoft amid a lot of initial developer pushback, seemingly misplaced.

  • First Official OpenAI Library for .NET Goes Beta

    Although it seems Microsoft and OpenAI have been deeply intertwined partners for a long time, they are only now getting around to releasing an official OpenAI library for .NET developers, joining existing community libraries.

Subscribe on YouTube