Change table name at runtime

后端 未结 7 1891
陌清茗
陌清茗 2020-12-17 03:22

Lets suppose that I have a db table with name Employee and a respective EF 6.0 db-first model.

Getting all rows of table Employee is done through q

相关标签:
7条回答
  • 2020-12-17 04:25

    I would do something like this:

    public partial class MyContext : DbContext
    {
        private readonly ITableNameProvider _tableNameProvider;
    
        public MyContext(ITableNameProvider tableNameProvider)
            : base("name=ConnectionStringName")
        {
            _tableNameProvider = tableNameProvider;
        }
    
        public virtual DbSet<MyGenericEntity> Templates { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<MyGenericEntity>()
                .ToTable(_tableNameProvider.GetTableName(), _tableNameProvider.GetSchemaName());
        }
    
    }
    

    I think it works in your scenario. The only problem would be OnModelCreating() is run once. Therefore if you use it in the same application, it'll take the first table name since it caches the result.

    0 讨论(0)
提交回复
热议问题