Search code examples
c#multi-tenantabp-framework

Inserting an entity with TenantId in abp.io framework


I have an entity below that, when I create, inserts with TenantId null. Is it necessary to use CurrentTenant.Id to set TenantId manually?

public class Hall : AuditedAggregateRoot<Guid>, IMultiTenant
{
    public string Name { get; set; }
    public string Location { get; set; }
    public string Explanation { get; set; }
    public Guid? TenantId { get; set; }
}

Solution

  • If you don't inherit from AsyncCrudAppService, then it is necessary to set TenantId yourself.

    protected void TryToSetTenantId(TEntity entity)
    {
        var tenantId = CurrentTenant.Id;
    
        if (!tenantId.HasValue)
        {
            return;
        }
    
        var propertyInfo = entity.GetType().GetProperty(nameof(IMultiTenant.TenantId));
    
        if (propertyInfo != null && propertyInfo.GetSetMethod() != null)
        {
            propertyInfo.SetValue(entity, tenantId, null);
        }
    }
    

    ABP Framework (abp.io) does not limit the case where you may want to create a host or other tenant entity within a tenant scope.

    References: