Joining
two tables’ data
The following code snippet shows how you can
join two tables’ data and display the result of query in DataGridView.
Query:
In the following query we are joining two
tables data, one is Customer and
second is Item and extracting which
customer buys which item and showing the query result in DataGridView.
var query =
from Customer c in
dc.Customers
join Item i in dc.Items
on c.ID equals
i.CustomerID
select new
{
c.ID,
c.Name,
itemName = i.Name,
i.Price
};
dataGridView1.DataSource = query;
We are joining two tables’ data on the basis
of primary-foreign key relation. Customer table has column name ID that is primary key in the table,
and in the table Item there is CustomerID which is foreign key. So we
can join these two tables and get those customers which buy something.
In
the above query: “select new“ usually
it is called as “Anonymous Type”,
means we just want to show the CustomerID,
his/her Name and the itemName which he/she buys and the Price of item.
0 comments:
Post a Comment