0

I'm fairly new in Entity Framework and web API. I'm trying to GET data from a table. But the table is going to be selected from different databases. So, there's multiple databases with the same tables and I need to select which database (I'm thinking [Fromuri]) I need to get the tables from. Right now I only have one database connected. Not sure if I need to add it all as a connection string or is there an easier way.

public IHttpActionResult Get()
{
    using (var MGC = new GC_BranchNameEntities())
    {
        var serializer = new JsonSerializer();
        var jsonIDSA = JsonConvert.SerializeObject(MGC.INV_LIVE_IDSA, Formatting.None);
        try
        {
            return Ok(jsonIDSA);
        }
        catch (Exception e)
        {
            return BadRequest("Error occured when retreiving IDSA data " + e.Message);
        }
    }
}

Can I do something like using(var MGC = new SelectdatabaseEntitiesusingParam) something like that?

Ben
  • 2,433
  • 5
  • 39
  • 69
J.P Masangcay
  • 759
  • 2
  • 10
  • 28
  • Do the databases have the same structure (tables, relations, columns)? If it is, using a diferent connection string for the data context would open connection to that database. [It is possible](http://stackoverflow.com/questions/6003085/how-do-i-programmatically-set-the-connection-string-for-entity-framework-code-fi) to create connection string for entity framework from code. – Martin Staufcik Oct 26 '15 at 04:36
  • @MartinStaufcik Yep, Completely identical. Except for the data of course. – J.P Masangcay Oct 26 '15 at 05:00

1 Answers1

1

There is a DbContext constructor overload that takes a connection string or name of a connection string as a parameter, and others that accept an existing DbConnection object.

Update:

Add a new constructor to your DbContext derived class, passing the parameter to the base constructor:

public GC_BranchNameEntities( string nameOrConnString ) :
    base( nameOrConnString )
{
}

Then, when instantiating your DbContext, pass in the name of the connection string to use (one defined in your config file) or an actual connection string. Alternatively, you can also create a constructor overload that accepts an existing DbConnection object (similarly to the nameOrConnString parameter) and pass that to the base constructor.

Moho
  • 15,457
  • 1
  • 30
  • 31