How to implement IModelCacheKeyFactory in EF Core

前端 未结 2 1723

The story: in our multi-tenant app (one PostgreSql db, multiple schemas) we need to use one DbContext against multiple schemas.

What I tried: holding a cache (Dictio

相关标签:
2条回答
  • 2020-12-10 17:21

    There actually have demo project in docs https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/DynamicModel adding post for convinience !

    0 讨论(0)
  • 2020-12-10 17:34

    Here is an example.

    Derived DbContext that replaces it's ModelCacheKey (and factory) with a Custom one.

    class MyDbContext : DbContext
    {
        public MyDbContext(string schema)
        {
            Schema = schema;
        }
    
        public string Schema { get; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder options)
            => options
                .UseSqlServer("...")
                .ReplaceService<IModelCacheKeyFactory, MyModelCacheKeyFactory>();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema(Schema);
    
            // ...
        }
    }
    

    The factory that creates the Context with a specific key.

    class MyModelCacheKeyFactory : IModelCacheKeyFactory
    {
        public object Create(DbContext context)
            => new MyModelCacheKey(context);
    }
    

    The custom ModelCacheKey per context.

    class MyModelCacheKey : ModelCacheKey
    {
        string _schema;
    
        public MyModelCacheKey(DbContext context)
            : base(context)
        {
            _schema = (context as MyDbContext)?.Schema;
        }
    
        protected override bool Equals(ModelCacheKey other)
            => base.Equals(other)
                && (other as MyModelCacheKey)?._schema == _schema;
    
        public override int GetHashCode()
        {
            var hashCode = base.GetHashCode() * 397;
            if (_schema != null)
            {
                hashCode ^= _schema.GetHashCode();
            }
    
            return hashCode;
        }
    }
    
    0 讨论(0)
提交回复
热议问题