Starts in:
2 DAYS
16 HRS
11 MIN
48 SEC
Starts in:
2 D
16 H
11 M
48 S
Open Closed

Is there a way to add [IgnoreMultiTenancy] on an Entity level instead of DbContext Level #8051


User avatar
0
Bryan-EDV created

I am referencing these docs: https://abp.io/docs/latest/framework/data/entity-framework-core#controlling-the-multi-tenancy

I would like to ensure that some entities always uses the host connection string, even if I am in a tenant context.

Based on the documentation, this can be done on the DbContext level, where all DbSet<Entity> defined in that context will be only using the host connection string.

Question is if there is a way to define this [IgnoreMultiTenancy] flag on the Entity level. I saw that there is a check here:

however i tried adding [IgnoreMultiTenancy] to the Entity but it doens't seem to work e.g.

Is there something I am missing? Thanks


20 Answer(s)
  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Hello ,

    Please check this https://github.com/abpframework/abp/issues/9828

    Thank you.

  • User Avatar
    0
    Bryan-EDV created

    Hi Anjali,

    It seems like the OP was asking about ignoring the [IgnoreMultiTenancy] decorator. My question is different, as I want to apply this [IgnoreMultiTenancy] decorator on an entity level.

    Otherwise, we may need to create a new DbContext for all entities which are IMultiTenant but still use Host DB Context (Even if the Tenant has its own DB Connection String)

  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Hello,

    oh is that the case, sorry it's my bad. I will check again and get back to you asap.

    Thanks

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    If your entity has implemented the IMultiTenant there is no way to ignore it.

  • User Avatar
    0
    Bryan-EDV created

    Thank you. The workaround I will then try is to implement a new DbContext class and apply the [IgnoreMultiTenancy] attribute

    I've Created a class called HostOnlyDbContext.cs

    [ConnectionStringName("Default")]
    [IgnoreMultiTenancy]
    public class HostOnlyDbContext : AbpSolution4DbContextBase&lt;HostOnlyDbContext&gt;
    {
        public DbSet&lt;Experience&gt; Experiences { get; set; } = null!;
    
        public HostOnlyDbContext(DbContextOptions&lt;HostOnlyDbContext&gt; options)
            : base(options)
        {
        }
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.SetMultiTenancySide(MultiTenancySides.Both);
    
            builder.Entity&lt;Experience&gt;(b =>
            {
                b.ToTable(AbpSolution4Consts.DbTablePrefix + "Experiences", AbpSolution4Consts.DbSchema);
                b.ConfigureByConvention();
                b.Property(x => x.TenantId).HasColumnName(nameof(Experience.TenantId));
                b.Property(x => x.Name).HasColumnName(nameof(Experience.Name));
            });
        }
    

    And also registered the DbContext in AbpSolution4EntityFrameworkCoreModule.cs

     public override void ConfigureServices(ServiceConfigurationContext context)
     {
         context.Services.AddAbpDbContext&lt;AbpSolution4DbContext&gt;(options =>
         {
             /* Remove "includeAllEntities: true" to create
              * default repositories only for aggregate roots */
             options.AddDefaultRepositories(includeAllEntities: true);
    
             options.AddRepository&lt;Conversation, Conversations.EfCoreConversationRepository&gt;();
         });
    
         context.Services.AddAbpDbContext&lt;HostOnlyDbContext&gt;(options =>
         {
             options.AddDefaultRepositories(includeAllEntities: true);
             options.AddRepository&lt;Experience, Experiences.EfCoreExperienceRepository&gt;();
         });
    

    Would this work? I am having trouble understanding how the original AbpSolution4DbContext is being injected and whether it is possible to reference AbpSolution4DbContext for the Conversation entity but use HostOnlyDbContext for the Experience entity.

    also, is there a way to migrate BOTH the AbpSolution4DbContext and HostOnlyDbContext during DB Migration? Currently it is only running migrations for AbpSolution4DbContext

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    I don't recommend that you do this.

    The IMultiTenant is used in frameworks everywhere.

  • User Avatar
    0
    Bryan-EDV created

    Hi Maliming,

    Just as context, our business requirement is that for some custom entities (e.g. AppBooks), that our data must reside only in the Host Database (even if tenant is using its own DB Connection String). But the data must still be accessible from the Tenant.

    Is there a better way to achieve this outcome in the ABP framework?

    Thank you

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    If your entity has implemented the IMultiTenant there is no way to achieve this.

  • User Avatar
    0
    Bryan-EDV created

    Hi Maliming,

    Noted on that. As I still need some filtering by TenantId, A possible workaround for me is to add TenantId without implementing IMultiTenant.

    Is there any way to automatically populate this TenantId field with the CurrentTenant? Thank you

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Noted on that. As I still need some filtering by TenantId, A possible workaround for me is to add TenantId without implementing IMultiTenant.

    You can override the ef core filter method. https://abp.io/docs/latest/framework/infrastructure/data-filtering?_redirected=B8ABF606AA1BDF5C629883DF1061649A#entityframework-core

    Is there any way to automatically populate this TenantId field with the CurrentTenant?

    The entity's TenantId has nothing to do with ICurrentTenant

    ICurrentTenant value coming from claims.

  • User Avatar
    0
    Bryan-EDV created

    Hi Maliming,

    Refering to documentation snippet below. As I would like to auto-populate my TenantIdCustom property (**not ** inherited from IMultiTenant), is there a way to implement the auto-population logic similar to how ABP framework auto populates TenantId?

    Will post a code implementation shortly

  • User Avatar
    0
    Bryan-EDV created

    Something like this? (I not sure if ICurrentTenant is available for dependency injection on a Entity level though)

    Injecting into DomainService should work right? But this is not desirable, as I would need to override the CreateAsync method for every DomainService for the entity. I would prefer if the Entity itself does the initialization, similar to classes implementing IMultiTenant

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    The tenantid set in the base class.

    You can call the YouEntityHelper.TrySetTenantId(this);

    This breaks the framework design and may cause uncertainty in related functions.

    
    public abstract class Entity : IEntity
    {
        protected Entity()
        {
            EntityHelper.TrySetTenantId(this);
        }
    }
    
    public static class YourEntityHelper
    {
        public static void TrySetTenantId(IEntity entity)
        {
            //if (entity is not IMultiTenant multiTenantEntity)
            //{
            //    return;
            //}
    
           //make sure entity is contains `TenantIdCustom`
    
            var tenantId = AsyncLocalCurrentTenantAccessor.Instance.Current?.TenantId;
            if (tenantId == multiTenantEntity.TenantIdCustom)
            {
                return;
            }
    
            ObjectHelper.TrySetProperty(
                multiTenantEntity,
                x => x.TenantIdCustom,
                () => tenantId
            );
        }
    }
    
  • User Avatar
    0
    Bryan-EDV created

    Thank you for the insights. As I do not want to deviate from the framework design, I will implement the manual assignment of TenantIdCustom upon entity creation (We forsee only a limited number of such entities)

    In addition, I've implemented a DataFilter within MyApplcaitionDbContext.cs

    protected bool IsMultiTenantInHostDb =&gt; DataFilter?.IsEnabled&lt;IMultiTenantInHostDb&gt;() ?? false;
    
    protected override bool ShouldFilterEntity&lt;TEntity&gt;(IMutableEntityType entityType)
    {
        if (typeof(IMultiTenantInHostDb).IsAssignableFrom(typeof(TEntity)))
        {
            return true; // Apply filter for entities implementing IMultiTenantInHostDb
        }
    
        return base.ShouldFilterEntity&lt;TEntity&gt;(entityType);
    }
    
    protected override Expression&lt;Func&lt;TEntity, bool&gt;&gt; CreateFilterExpression&lt;TEntity&gt;(ModelBuilder modelBuilder)
    {
        var expression = base.CreateFilterExpression&lt;TEntity&gt;(modelBuilder);
    
        if (typeof(IMultiTenantInHostDb).IsAssignableFrom(typeof(TEntity)))
        {
            // Get the current tenant ID
            var currentTenantId = CurrentTenant.Id;
            Console.WriteLine(&quot;currentTenantId:&quot;);
            Console.WriteLine(currentTenantId);
    
            // Create the filter expression
            Expression&lt;Func&lt;TEntity, bool&gt;&gt; tenantFilter = e =&gt;
                !IsMultiTenantInHostDb ||
                (EF.Property&lt;Guid?&gt;(e, &quot;TenantIdCustom&quot;) == currentTenantId || EF.Property&lt;Guid?&gt;(e, &quot;TenantIdCustom&quot;) == null);
    
            expression = expression == null ? tenantFilter : QueryFilterExpressionHelper.CombineExpressions(expression, tenantFilter);
        }
    
        return expression;
    }
    

    as per your reference for ef core filter: https://abp.io/docs/latest/framework/infrastructure/data-filtering?_redirected=B8ABF606AA1BDF5C629883DF1061649A#entityframework-core

    However the currentTenantId coming as null, even when logged in as a tenant. Is there some issue with my usage of CurrentTenant.Id?

  • User Avatar
    0
    Bryan-EDV created

    Hi maliming,

    I've managed to resolve the issues and get the desired implementation. Give me a few hours to add the code snippets here for others to reference.

    Thank you

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Good news 👍

  • User Avatar
    0
    Bryan-EDV created

    Creating a knowledge article on this topic and will post the link here in a bit

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    : )

  • User Avatar
    0
    Bryan-EDV created

    Posted this article on the topic: https://medium.com/@kaffeeebene/abp-in-depth-storing-key-tenant-data-in-the-host-database-while-keeping-the-rest-in-tenant-ca2aca0e4cd2

    Thanks!

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    👍

    If you like, you can post your article to abp community.

    https://abp.io/community/posts/submit

Made with ❤️ on ABP v9.1.0-preview. Updated on November 20, 2024, 13:06