Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Linq: Relationship Code Sample

4.70/5 (11 votes)
16 May 2011CPOL 28.7K   854  
How to Implement Relationship in LINQ using C# and ASP.NET for Beginners

Introduction

This sample shows how to implement Relationship Using LINQ in C# and ASP.NET for a beginner.

How To Do

  1. Create an ASP.NET Web application using C# in Visual Studio 2008.

    File-> New -> Project -> ASP.NET Web Application

    Image 1

    Image 2

  2. Add a database file to app_data - "student.mdf".
    1. Right Click App_Data, Add->New Item->Data->SQL Server DataBase.
    2. Give name Student.mdf.

      Image 3

    3. Go to the Server Explore, Expand Student DataBase, In Tables, Add New Table
    4. Add two tables, Student and Mark.

      Table: StudentColumns: StudentID int, Name nvarchar(50), Age int

      Table: Mark
      Columns: StudentID int, Class nvarchar(50), Mark int

      Add some sample data for the Student and Mark tables, (student id should be same in Mark and Student table)

      For that, right click the table and click show table data, you can add data here.

      Image 4

  3. LINQ to SQL

    Right click the solution, add New Item->Data-> Linq to SQL Class.

  4. Give Name "LinqToStudents.dbml".

    Image 5

  5. Pick SQL Server explore, drag the two tables to the window:

    Image 6

    Save the Project.

  6. Drag a DataGrid view to the Default.aspx Page:

    Image 7

  7. Use the below code snippets pageload of the project:
    C#
    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, };      
    C#
    GridView1.DataSource = query; 
    GridView1.DataBind(); 

    Image 8

Run the project by pressing F5.

History

  • Release 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)