We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Matthew Hill • 3 years ago

Hi Gunnar, your posts are very useful. I used the example in this post and it worked, however I'm having difficulty figuring out how to get a tenantid saved to each entity. I've tried adding defaults but they don't seem to get applied. The TenantID just gets saved as zeros "00000000-0000-0000-0000-000000000000".

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<todoitem>(entity =>
{
entity.Property(e => e.tenantID)
.ValueGeneratedOnAdd()
.HasDefaultValue(_tenantProvider.GetTenantId());

});
}

Victor Perez • 3 years ago

I know it's been a while

But follow.

The Model resulting from the ModelCreating method is used by the Framework at different times.

One in time of "Update-Database", and another at run time.

At run time the tenant Guid is populated, but at Update-database time does not.

This great article does what you need using SQL Server SESSION_CONTEXT.

https://www.carlrippon.com/...

Victor Parez

Damian • 2 years ago

Hi
You can also overwrite the SaveChanges () method in MultitenantDbContext
In this way:

public override int SaveChanges()
{
foreach (var entity in ChangeTracker.Entries().Where(e => e.State == EntityState.Added).Select(e => e.Entity as Person).ToList())
{
entity.TenantId = entity.TenantId != Guid.Empty ? entity.TenantId : _tenantProvider.GetTenantId();
}

return base.SaveChanges();
}

Adam • 1 year ago

Wouldn't injecting ITenantProvider into MultiTenantDbContext, and vise versa, throw a circular reference error?

Jos Krause • 7 months ago

There are two DbContext for this purpose, one purely for Tenant purposes, and the other that contains the shared data.