Linq for Joining multiple tables
How to write query for joining more tables.I have a patient id for all tables as common and i need to retrieve all values what are there in various tables.can you please tell me how to do that?..
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Mar 26, 2014, 9:39 AM
So, if you were joining two tables and table1 had columns called 'name' and 'patientid' and table2 had columns called 'gender', 'age' and 'patientid' your query would be:
var k = from p in context.table1
join p1 in context.table2 on p.patientid equals p1.patientid
select new
{
name = p.name,
patientid = p.patientid,
gender = p1.gender,
age = p1.age
};
Lawrence PondPosted Apr 12, 2014, 3:03 AM
from c in Customers
join p in Purchases on c.patientID equals p.patient ID
select new
{
c.Name, p.Description, p.Price
};
var fluentSyntax =
Customers.Join ( // outer collection
Purchases, // inner collection
c => c.patientID, // outer key selector
p => p.patientID, // inner key selector
(c, p) => new // result selector
{
c.Name, p.Description, p.Price
}
);
Pratap PatelPosted Mar 28, 2014, 2:42 AM
For example, You have two tables as below:
Table - Department
DeptID(PK),DeptName
Table - Employee
EmpID(PK),EmpName,DeptId(FK),Salary,......
Then in case you create a class like below
class EmployeeDetails
{
int EmpId,
String EmpName,
double Salary,
String Department //To store name of department from Department table
}
Now, You write a LINQ query as below and store result in List of class EmployeeDetails
List
join dept in Department
on emp.DeptId equals dept.DeptId
select new EmployeeDetails
{
EmpId = emp.EmpID,
EmpName = emp.EmpName,
Salary = emp.Salary,
Department = dept.
}).ToList();
I hope you will got it.
Thank you
VulpesPosted Mar 27, 2014, 6:17 AM
If I can just demonstrate using a local query:
The output is:
Sasi ReddyPosted Mar 27, 2014, 3:46 AM
Abhay ShankerPosted Mar 26, 2014, 7:57 AM
http://www.c-sharpcorner.com/UploadFile/54db21/joins-using-linq-in-C-Sharp/
http://www.mssqltips.com/sqlservertip/3169/understanding-linq-to-join-multiple-tables-where-null-match-are-expected/
Abhay ShankerPosted Mar 26, 2014, 7:56 AM
var customers = Customer.SampleData();
var orders = Order.SampleData();
var q = from c in customers
join o in orders on c.CustomerID equals o.CustomerID into j
from order in j.DefaultIfEmpty()
select new
{
LastName = c.LastName,
//set no order when we have a null value
OrderNumber = order == null ? "(no order)" : order.OrderNumber};
};
Jignesh TrivediPosted Mar 26, 2014, 7:49 AM
hi,
using "join" statement you join two or more tables
like
var k = from p in context.table1
join p1 in context.table2 on p.patientid equals p1.patientid
join p2 in context.table2 on p.patientid equals p2.patientid
select p;
above code is example of inner join.
hope this will help you.