0

I have a MVC project(data base first) with one SQL connection string.for applying this connection I use this way and it's connected correctly:
http://www.c-sharpcorner.com/UploadFile/8a67c0/database-first-approach-with-Asp-Net-mvc-step-by-step-part-2/

But, My problem is about applying another connection at run time with MySQL database.In fact, I have several forms which need to SQL connection and several forms which need MySQL connection.On the other hands, MySQL connection must be set at run time.

So, I have two important questions:

1-How can I set MySQL connection string at run time (in associated my model)
2-How can I switch between two connections in different views in running project.

for more explanation you could see my model for creating MySQL connection as below:(these fields are set in view, after posting view connection must be connected)

 public partial class BPMEngine
{
    public int EngID { get; set; }
    public string EngName { get; set; }
    public string DBServer { get; set; }
    public string DBName { get; set; }
    public string DBUserName { get; set; }
    public string DBPass { get; set; }
    public string EngURL { get; set; }
    public string AppRootPath { get; set; }
}
Tanner
  • 22,205
  • 9
  • 65
  • 83
Lili.brh
  • 25
  • 1
  • 7

1 Answers1

0

In application settings you specify connection string and in context class you pass the connections string.

I would suggest you to specifiy 2 (or as much as you need) connection strings and use multiple context classes, each for "communicating" with other DB.

Example:

in App.config:

<connectionStrings>
  <add name="conn_str_number_1" .../>
  <add name="conn_str_number_2" .../>
</connectionStrings>

Context classes:

class MyContext1 : DbContext
{
    public MyContext() : base("name=conn_str_number_1")
    {
         //...
    }
    //...
}

Another one:

class MyContext2 : DbContext
{
    public MyContext() : base("name=conn_str_number_2")
    {
         //...
    }
    //...
}

And in code use both context classes, so you can interact with both DBs.

To switch connection string at run-time you can use contextClass.Database.Connection.ConnectionString property. More info about it here.

There, also we can read: DbContext has a constructor overload that accepts the name of a connection string or a connection string itself. Implement your own version and pass it to the base constructor:

public class MyDbContext : DbContext
{
    public MyDbContext( string nameOrConnectionString ) 
        : base( nameOrConnectionString )
    {
    }
}

But you have to specify all connection strings before running program :)

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69