Monday, March 9, 2009

Multiple Joins in LINQ



Hi All,
This Post will show how to implement multiple Joins in LINQ.



using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

public partial class JoinsInLINQ : System.Web.UI.Page

{

DemoDataContext DC = new DemoDataContext();

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

Bind();

}

}

private void Bind()

{

// How to Apply Joins in LINQ

var items = from P in DC.Emps

join Ep in DC.EmpProducts on P.SINo equals Ep.SINo

join TT in DC.TextTables on P.SINo equals TT.SINo

select new

{

Name = P.Name,

Age = P.Age,

Country = P.Country,

State = P.State

};

GVInJoins.DataSource = items;

GVInJoins.DataBind();

}

}


On Debugging the Query we will find it like as........



{SELECT [t0].[Name], [t0].[Age], [t0].[Country], [t0].[State]
FROM [dbo].[Emp] AS [t0]
INNER JOIN [dbo].[EmpProduct] AS [t1] ON [t0].[SINo] = [t1].[SINo]
INNER JOIN [dbo].[TextTable] AS [t2] ON [t0].[SINo] = [t2].[SINo]
}




Now finally Bind the Output to the Gridview and its ready now...




Thanks to LINQ :)


Thanks,

Nitin Sharma