How to Join Two Tables From Different Databases Using Entity Framework

Introduction

 
This article explains how to join two different tables from two different databases, or we may say how to join two tables from two different contexts, in Entity Framework.
 
The first thing we should remember is that it is not possible in Entity Framework to join two or more entities of different contexts directly. Then the question arises on how to join tables that are from a different context? So for that, we can create a memory object of both contexts and join them in memory and then return it back to the caller function. The following code shows how to do this.
 
Step 1
 
First of all, create two contexts that refer to two different databases. For creating the Entity Framework model click here.
 
In this example, I use the following two tables of two different databases.
  1. WILMO_DBContext is the context for the following model.
     
    Navigation Property
     
    This table contains information about student information.
     
  2. Wst_SMSContext is the context for the following model.
     
    sms recive
     
    This table contains information on the student examination information.
     
    Remember: Both tables are in different databases.
     
    For joining these two tables first create two different contexts as of above. If you are new to Entity Framework then click here to understand how to create a context in EF.
Step 2
 
Now create a class that will store information about the student results that we will get after joining both tables.
 
Actually I need to get the student name from tblstudent by mobile number.
  1. public class SmsResult  
  2. {  
  3.     public int Id { getset; }  
  4.     public Nullable<int> UserId { getset; }  
  5.     public string Sender { getset; }  
  6.     public string Receiver { getset; }  
  7.     public string StudentName { getset; }  
  8.     public string Message { getset; }  
  9.     public System.DateTime OnDate { getset; }  
  10.     public System.DateTime TsSent { getset; }          
  11.     public int ExamResult { getset; }  
  12.     public int NoOfExam { getset; }  
  13. }  
Step 3
 
Write the following function in the code behind to join both tables.
  1. public IEnumerable<SmsResult> SelectStudentList()  
  2. {  
  3.        IEnumerable<SmsResult> studentwilmo = null;  
  4.        using (WILMO_DBContext students = new WILMO_DBContext())  
  5.        {  
  6.               studentwilmo = students.tblstudents.Select(x => new SmsResult()  
  7.               {  
  8.                     StudentName = x.Studentname,  
  9.                     Sender = x.Mobileno  
  10.                     ).Distinct().ToList();  
  11.               }  
  12.              using (Wst_SMSContext smsDb = new Wst_SMSContext())  
  13.              {  
  14.                    string keys = ConfigurationManager.AppSettings["Keys"];  
  15.                   var Temp = smsDb.sms_receive.AsEnumerable().Select(i => new  
  16.                   {  
  17.                        Sender = i.Sender,  
  18.                        ExamResult = i.ExamResult  
  19.                   }).ToList();  
  20.   
  21.                  IEnumerable<SmsResult> TotalScore = Temp.Join(studentwilmo, x => x.Sender, y => y.Sender,  
  22.                     (x, y) => new  
  23.                  {  
  24.                         Sender = x.Sender,  
  25.                         ExamResult = x.ExamResult,  
  26.                         StudentName = y.StudentName  
  27.                  }).GroupBy(x => new { x.Sender, x.StudentName })  
  28.                             .Select(s => new SmsResult()  
  29.                              {  
  30.                                     NoOfExam = s.Count(p => p.Sender != null),  
  31.                                     ExamResult = s.Sum(b => Convert.ToInt32(b.ExamResult)),  
  32.                                     Sender = s.Key.Sender,  
  33.                                     StudentName = s.Key.StudentName  
  34.                               }).ToList();  
  35.                 return TotalScore;  
  36.             }  
  37.       } 
Step 3
 
Drag and drop a grid view control with the following Bound Field.
  1. <asp:GridView ID="gvStudents" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" AutoGenerateColumns="False">  
  2.        <Columns>  
  3.             <asp:TemplateField HeaderText="Sl No">  
  4.                 <ItemTemplate>  
  5.                     <%#Container.DataItemIndex+1 %>  
  6.                 </ItemTemplate>  
  7.                 <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />  
  8.             </asp:TemplateField>     
  9.              
  10.                      <asp:BoundField DataField="Studentname" HeaderText="Name"  
  11.                 SortExpression="Sender" />  
  12.             <asp:BoundField DataField="Sender" HeaderText="Sender"  
  13.                 SortExpression="Sender" />             
  14.               
  15.              
  16.             <asp:BoundField DataField="ExamResult" HeaderText="Score"  
  17.                 SortExpression="ExamResult" />  
  18.               
  19.             <asp:BoundField DataField="NoOfExam" HeaderText="No Of Exam"  
  20.                 SortExpression="ExamResult" />  
  21.         </Columns>  
  22.   
  23.   
  24.         <FooterStyle BackColor="White" ForeColor="#000066" />  
  25.         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  26.         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  27.         <RowStyle ForeColor="#000066" />  
  28.         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  29.         <SortedAscendingCellStyle BackColor="#F1F1F1" />  
  30.         <SortedAscendingHeaderStyle BackColor="#007DBB" />  
  31.         <SortedDescendingCellStyle BackColor="#CAC9C9" />  
  32.         <SortedDescendingHeaderStyle BackColor="#00547E" />  
  33.     </asp:GridView>  
  34.             </ContentTemplate>  
Step 4
 
Call the function in the form of load events of the webpage and bind the result of that function with the grid view controls.
  1. public void SelectStudentList(GridView gv)  
  2. {  
  3.       gv.DataSource = bel.SelectStudentList().Take(20);  
  4.       gv.DataBind();  
  5.       gv.EmptyDataText = "No Data Found.";  
  6. }  
  7.  
  8. protected void Page_Load(object sender, EventArgs e)  
  9. {  
  10.     if (!IsPostBack)  
  11.     {  
  12.            SelectStudentList(gvStudents);  
  13.     }
  14. }   
Now we get output like:
 
join output
 

Summary

 
This article showed how to join two tables of different databases or different contexts using Entity Framework (EF).
 
Thanks.
 
I would like to get feedback from my readers. Please post your feedback, question, or comments about this article.