Search code examples
databaseframeworksentityconfigure

How do I configure Entity Framework to use whatever database is in the connection string


The code I inherited has an OnModelCreating(ModelBuilder modelBuilder) , and inside that method , for each entity, it does entity.ToTable("someTableName", "someDatabaseName");

Instead of specifying "someDatabaseName" in entity.ToTable("someTableName", "someDatabaseName"); how do I configure EF to use whatever db is inside the connection string?

One solution is to go inside OnModelCreating(ModelBuilder modelBuilder) and make the string "someDatabaseName" into a variable, then set that variable based on the connection string, (but something about that seems wonky , and leaves me wondering what is a better, more preferred way?)

//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?
        ...
    }
}

Solution

  • The solution was to change this

    entity.ToTable("table1", "someDatabaseName"); 
    

    to this

    entity.ToTable("table1");