How to insert data by using LINQ to SQL concept
How to insert data by using LINQ to SQL concept
298
24-Mar-2025
Updated on 20-Apr-2025
Khushi Singh
20-Apr-2025When working with LINQ to SQL in C#, data insertion requires proper implementation of data context alongside mapped classes. The C# classes and LINQ queries enable LINQ to SQL to automatically perform database table mapping for CRUD operations.
The process of data insertion with LINQ to SQL functions as follows:
Step-by-Step Overview (Theory)
Create a DataContext: This represents your database and handles the connection.
Define Entity Classes: These are mapped to your database tables using the Object Relational Designer (DBML file).
Create an Object: Instantiate the entity class and populate its properties with data.
Insert the Object: Use the
InsertOnSubmit()method on the corresponding table.Submit Changes: Call
SubmitChanges()on theDataContextto push the new record into the database.Code Example
This example uses
MyDataContextas the LINQ to SQL data context which came from a .dbml file and Student represents the table-mapped class. The insertion sequence requires you to create a Student object with value assignments followed by a call toSubmitChanges()to implement the changes.