+92 332 4229 857 99ProjectIdeas@Gmail.com

How to join two tables data (LINQ To SQL)

Joining two tables’ data
The following code snippet shows how you can join two tables’ data and display the result of query in DataGridView.

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
               itemName = i.Name,
     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 newusually 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.