Click here to Skip to main content
15,903,033 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am developing an API in C#, using entity framework data model. I am connected to an existing database and can get or post data as i wish too. But now i want to fetch some data which is present in another database and display the information of an employee from two different databases.
Below is the code through which i am retrieving data from a single database.

What I have tried:

public HttpResponseMessage Get(int EmployeeId)
{
  var masterInfo = entities.Empmasters.where(e => e.EmployeeId == 
                                             EmployeeId).FirstOrDefault();

  if (masterInfo == null)
  {
     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No info");
  }
  else
  {
    return Request.CreateResponse(HttpStatusCode.OK, masterInfo);
  }
Posted
Updated 31-Jul-18 21:31pm
v2

1 solution

You can create another DBContext and entities for another database.
Or you could create new API project and call its endpoint to get other information.
Or you could create a Stored Procedure that call another database, and call the stored procedure in your current DBContext.
 
Share this answer
 
Comments
Tausif Khan 1-Aug-18 5:24am    
@keviniano: Suppose i create another DBContext and entities to connect to my second database, then how do i maintain the connection string throughout the action. For eg: In my case it will be an employee logging in, so some of his information will be retrieved from one database n some from another. Now he tries to apply a leave again in which the record will be saved in the table of my second database. So how do i maintain the same connection string till he manages to log out of the application. Sorry for the long comment.
Keviniano Gayo 1-Aug-18 5:55am    
You will setup different connection string for each DBContext.
class EmployeeDB : DBContext
public EmployeeDB() : base("name=employeeConnectionString")

class LeaveDB : DBContext
public LeaveDB() : base("name=leaveConnectionString")

app.config:
<add name="employeeConnectionString"
providerName="System.Data.SqlClient"
connectionString="Server=.\SQLEXPRESS;Database=Blogging;Integrated Security=True;"/>

<add name="leaveConnectionString"
providerName="System.Data.SqlClient"
connectionString="Server=.\SQLEXPRESS;Database=Blogging;Integrated Security=True;"/>

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900