Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Last active October 27, 2021 21:42
Show Gist options
  • Save dcomartin/d88f58f02bfa48840b19b0c001ad8500 to your computer and use it in GitHub Desktop.
Save dcomartin/d88f58f02bfa48840b19b0c001ad8500 to your computer and use it in GitHub Desktop.
using System;
using Microsoft.EntityFrameworkCore;
namespace MultiTenant
{
public class Order
{
public Guid OrderId { get; set; }
public Guid TenantId { get; set; }
// Whatever other properties on on the order
}
public class OrderDbContext : DbContext
{
private readonly Token _token;
public DbSet<Order> Orders { get; set; }
public OrderDbContext(Token token)
{
_token = token;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().HasKey(x => x.OrderId);
modelBuilder.Entity<Order>().HasQueryFilter(b => b.TenantId == _token.TenantId);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("MultiTenant");
}
public delegate OrderDbContext TenantFactory(Token token);
public static OrderDbContext Factory(Token token)
{
return new OrderDbContext(token);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment