Emit DbContext.OnModelCreating on every context creation

后端 未结 2 728
别那么骄傲
别那么骄傲 2021-01-14 13:52

I use entity framework code first to work with my database. I have several tables with different names but same structure, and this tables dynamically appears in database. H

2条回答
  •  萌比男神i
    2021-01-14 14:23

    There is a built-in feature which may address your issue : `IDbModelCacheKey ; the implementation of which is to be registered in your configuration. The point is to generate a different key for your different contexts.

    I would go for something like :

    First, the configuration

    public class EntityFrameworkConfiguration: DbConfiguration
    {
        public EntityFrameworkConfiguration()
        {
            this.SetModelCacheKey(ctx => new EntityModelCacheKey((ctx.GetType().FullName + ctx.Database.Connection.ConnectionString).GetHashCode()));
        }
    }
    

    Then the implementation of the IDbModelCacheKey

    public class EntityModelCacheKey : IDbModelCacheKey
    {
        private readonly int _hashCode;
    
        public EntityModelCacheKey(int hashCode)
        {
            _hashCode = hashCode;
        }
    
        public override bool Equals(object other)
        {
            if (other == null) return false;
            return other.GetHashCode() == _hashCode;
        }
    
        public override int GetHashCode()
        {
            return _hashCode;
        }
    }
    

    Finally, your DataContext

    public class DataContext : DbContext
    {
    
      string setElementsTableId; 
    
      // use the setElementsTableId as extended property of the 
      // connection string to generate a custom key
      public DataContext(string setElementsTableId)
            : base(ConfigurationManager.ConnectionStrings["RepositoryConnectionString"] 
     + "; Extended Properties=\"setElementsTableId=" + setElementsTableId + "\"")
      {
        this.setElementsTableId = setElementsTableId;
      }
    
      public DbSet SetElements { get; set; } 
    
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
        if (!string.IsNullOrEmpty(setElementsTableId))
        {
            modelBuilder.Entity().Map(x => x.ToTable(setElementsTableId)); 
        }
      }
    }
    

    I hope this will be of some help

提交回复
热议问题