Loading [Contrib]/a11y/accessibility-menu.js
Back
Close

Multi-tenant ASP.NET Core 7 - Defensive database context

gpeipman
1,604 views

Defensive database context

To make sure that data from different tenants doesn't get mixed in multi-tenant application we can add some defensive behaviour to multi-tenant database context to build additional safety net for application developers.

The following demonstrates defensive database context and it uses the following classes:

  • ITenantProvider - interface for tenant providers,
  • DummyTenantProvider - tenant provider for demo purposes,
  • BaseEntity - base class for all entities,
  • Person - sample entity type for this demo,
  • CrossTenantUpdateException - exception type for operations that use data from multiple tenants,
  • SampleDbContext - defensive database context.

The sample below creates new instance of database context, adds two instances of Person entities that belong to different tenants and then saves changes. If cross-tenant operation exception is thrown then tenant ID-s involved to incident are written out.

Click to run the .NET Core Web app.
·using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace EFDefensive
{
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

References

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants