如何配置 Entity Framework 以使用连接字符串中的任何数据库
How do I configure Entity Framework to use whatever database is in the connection string
我继承的代码有一个 OnModelCreating(ModelBuilder modelBuilder)
,在该方法内部,对于每个实体,它 entity.ToTable("someTableName", "someDatabaseName");
我如何配置 EF 以使用连接字符串中的任何数据库,而不是在 entity.ToTable("someTableName", "someDatabaseName");
中指定“someDatabaseName”?
一个解决方案是进入 OnModelCreating(ModelBuilder modelBuilder)
并将字符串“someDatabaseName”变成一个变量,然后根据连接字符串设置该变量,(但有些事情看起来很奇怪,让我想知道是什么是更好、更受欢迎的方式吗?)
//This code runs before OnModelCreating()
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseMySQL(_connectionString);
//I wrongly assume the context would be using the db from this conn string,
//but it's not, it's using the database "someDatabaseName" from OnModelCreating below
}
}
//after OnConfiguring, then this code runs
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");
modelBuilder.Entity<SomeClass>(entity =>
{
entity.ToTable("table1", "someDatabaseName"); //i could make "someDatabaseName a variable, but surely there is a better way?
...
}
}
解决方案是改变这个
entity.ToTable("table1", "someDatabaseName");
至此
entity.ToTable("table1");
我继承的代码有一个 OnModelCreating(ModelBuilder modelBuilder)
,在该方法内部,对于每个实体,它 entity.ToTable("someTableName", "someDatabaseName");
我如何配置 EF 以使用连接字符串中的任何数据库,而不是在 entity.ToTable("someTableName", "someDatabaseName");
中指定“someDatabaseName”?
一个解决方案是进入 OnModelCreating(ModelBuilder modelBuilder)
并将字符串“someDatabaseName”变成一个变量,然后根据连接字符串设置该变量,(但有些事情看起来很奇怪,让我想知道是什么是更好、更受欢迎的方式吗?)
//This code runs before OnModelCreating()
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseMySQL(_connectionString);
//I wrongly assume the context would be using the db from this conn string,
//but it's not, it's using the database "someDatabaseName" from OnModelCreating below
}
}
//after OnConfiguring, then this code runs
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");
modelBuilder.Entity<SomeClass>(entity =>
{
entity.ToTable("table1", "someDatabaseName"); //i could make "someDatabaseName a variable, but surely there is a better way?
...
}
}
解决方案是改变这个
entity.ToTable("table1", "someDatabaseName");
至此
entity.ToTable("table1");