Base solution for your next web application
Open Closed

Switching Between Host and Tenants #2668


User avatar
0
bilalhaidar created

Hi, In the documentation it says the following.

So, if we are retrieving data for entities that have IMustHaveTenant, do we need to call SetTenantId explicitly? Isn't that retrieved from Session. Or is it a must to always call SetTenantId?

Thanks

Switching Between Host and Tenants
While working on a multitenant application database, we should know the current tenant. By default, it's obtained from IAbpSession (as described before). We can change this behaviour and switch to other tenant's database. Example:

public class ProductService : ITransientDependency
{
    private readonly IRepository<Product> _productRepository;
    private readonly IUnitOfWorkManager _unitOfWorkManager;

    public ProductService(IRepository<Product> productRepository, IUnitOfWorkManager unitOfWorkManager)
    {
        _productRepository = productRepository;
        _unitOfWorkManager = unitOfWorkManager;
    }

    [UnitOfWork]
    public virtual List<Product> GetProducts(int tenantId)
    {
        using (_unitOfWorkManager.Current.SetTenantId(tenantId))
        {
            return _productRepository.GetAllList();
        }
    }
}
SetTenantId ensures that we are working on given tenant data, independent from database architecture:

If given tenant has a dedicated database, it switches to that database and gets products from it.
If given tenant has not a dedicated database (single database approach, for example), it adds automatic TenantId filter to query get only that tenant's products.
If we don't use SetTenantId, it gets tenantId from session, as said before.

2 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    You don't have to call SetTenantId, both IMayHaveTenant and IMustHaveTenant uses TenantId from current session.

  • User Avatar
    0
    bilalhaidar created

    Thanks :)