Linq: Relationship Code Sample
Introduction
This sample shows how to implement Relationship Using LINQ in C# and ASP.NET for a beginner.
How To Do
- Create an ASP.NET Web application using C# in Visual Studio 2008.
File-> New -> Project -> ASP.NET Web Application
- Add a database file to
app_data- "student.mdf".- Right Click App_Data, Add->New Item->Data->SQL Server DataBase.
- Give name Student.mdf.
- Go to the Server Explore, Expand Student DataBase, In Tables, Add New Table
- Add two tables,
StudentandMark.Table:
StudentColumns:StudentID int,Name nvarchar(50),Age intTable:
Mark
Columns:StudentID int,Class nvarchar(50),Mark intAdd some sample data for the
StudentandMarktables, (student id should be same inMarkandStudenttable)For that, right click the table and click show table data, you can add data here.
- LINQ to SQL
Right click the solution, add New Item->Data-> Linq to SQL Class.
- Give Name "LinqToStudents.dbml".
- Pick SQL Server explore, drag the two tables to the window:
Save the Project.
- Drag a
DataGridview to the Default.aspx Page: - Use the below code snippets pageload of the project:
LinqToStudentsDataContext linqStud = new LinqToStudentsDataContext(); var query = from s in linqStud.Students join h in linqStud.Marks on s.StudentID equals h.StudentID select new {h.StudentID ,s.Name, };
GridView1.DataSource = query; GridView1.DataBind();
Run the project by pressing F5.
History
- Release 1
Post Comment
3KCr9c Thanks for the blog post. Great.