I try to use the global query filters to implement multi-tenancy in an ASP.NET Core web application. At the moment, I have a separate database for each tenant and configure the context in the startup.cs like that:
services.AddDbContext<dbcontext>((service, options) =>
options.UseSqlServer(Configuration[$"Tenant:{service.GetService<ITenantProvider>().Current}:Database"])
.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)),
contextLifetime: ServiceLifetime.Scoped, optionsLifetime: ServiceLifetime.Scoped);
This works fine. Now the customer doesn't want a separate database for each tenant anymore so I added a teanntId
colum to each table and want to leverage the global query filters to implement that.
As described in the documentation, I can add the query filter in the OnModelCreating
method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().Property<string>("TenantId").HasField("
modelBuilder.Entity<Blog>().HasQueryFilter(b => EF.Property<string>(b, "TenantId") == _tenantId);
}
But I am using the database first approach so each time I generate the model I will lose that configuration. Is there any other way to configure the global query filter like using the DbContextOptionsBuilder
?
I am using EF Core 2.1.2.