efcore 多租户动态设置查询schema

想象一下,你有一个多租户的系统,数据分别存储在不同的schema中,现在用户需要指定schema,从不同的schema中查询数据。则可按照如下进行

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata.Builders;


namespace Multi_Tenant_Dynamic_Schema.Models
{
    public class Test
    {
        public int ID { get; set; }

        public string Name { get; set; }
    }

    public class TestConfig : IEntityTypeConfiguration<Test>
    {
        public void Configure(EntityTypeBuilder<Test> builder)
        {
            builder.ToTable("test");
            builder.HasKey(t => t.ID);
            builder.Property(t => t.ID).HasColumnName("id");
            builder.Property(t=>t.Name).HasColumnName("name");
        }
    }


    public class CustomDbContext : DbContext
    {
        public string _schema { get; set; }
        public CustomDbContext(DbContextOptions<CustomDbContext> options)
            : base(options)
        {
        }

        public DbSet<Test> Tests { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema(_schema);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);

            base.OnModelCreating(modelBuilder);
        }

    }



    public class DbSchemaAwareModelCacheKeyFactory : IModelCacheKeyFactory
    {

        public object Create(DbContext context)
        {
            return new
            {
                Type = context.GetType(),
                Schema = context is CustomDbContext schema
                    ? schema._schema
                    : null
            };
        }
    }
}

其中我们在OnModelCreating中指定了schema,需要注意的是OnModelCreating只会执行一次,因为为了提高performance,efcore对数据进行了缓存,我们需要重写IModelCacheKeyFactory

DI

builder.Services.AddHttpContextAccessor();

builder.Services.AddDbContext<CustomDbContext>((serviceProvider, options )=>
{
    options.UseNpgsql(@"Host=192.168.214.133;Port=32222;Database=postgresdb;Username=postgresadmin;Password=admin123")
    .LogTo(Console.WriteLine, new[] { DbLoggerCategory.Database.Command.Name }, LogLevel.Information)
                   .EnableSensitiveDataLogging()
                   .ReplaceService<IModelCacheKeyFactory, DbSchemaAwareModelCacheKeyFactory>(); ; // Optional: Log sensitive data such as parameter values
    

    //var schema = serviceProvider.GetRequiredService<IHttpContextAccessor>()?.HttpContext?.Request.Headers["Schema"].ToString() ?? "public";

});

使用

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Multi_Tenant_Dynamic_Schema.Models;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Multi_Tenant_Dynamic_Schema.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        
        private readonly CustomDbContext  _customDbContext;

        public ValuesController(CustomDbContext customDbContext)
        {
            _customDbContext = customDbContext;
        }


        // GET api/<ValuesController>/5
        [HttpGet]
        public async Task<List<Test>> Get(string schema)
        {
            _customDbContext._schema = schema;
            return  await _customDbContext.Tests.ToListAsync();
        }

        
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值