linq
  1. linq-modifying-database-data

Modifying Database Data using LINQ to SQL

LINQ to SQL provides a simple and easy way to modify database data using object-oriented programming techniques. In this tutorial, we'll discuss how to modify database data using LINQ to SQL.

Syntax

using (var db = new DataContext())
{
    // Query data
    var record = db.TableName.FirstOrDefault(x => x.Id == id);

    // Modify data
    record.ColumnName = "New Value";

    // Save changes
    db.SubmitChanges();
}

Example

Let's assume we have a Customer table in our database with the following schema:

Column Name Data Type
Id int
Name varchar
Email varchar

Now, let's modify the data of a specific record in the Customer table using LINQ to SQL.

using (var db = new DataContext())
{
    // Query data
    var customer = db.Customers.FirstOrDefault(x => x.Id == 1);

    // Modify data
    customer.Name = "John Smith";
    customer.Email = "john.smith@example.com";

    // Save changes
    db.SubmitChanges();
}

In this example, we are querying the Customer table for a customer with Id equal to 1. Once we have the record, we modify the Name and Email fields and then save the changes using the SubmitChanges() method.

Output

There is no output for this code. However, the specified record in the database will be updated with the new values provided.

Explanation

In the above example, we used the DataContext class to connect to the database. Then, we used the FirstOrDefault() method to fetch the record from the Customers table with the specified Id. Once we have the record, we modify the Name and Email fields and then save the changes using the SubmitChanges() method.

Use

LINQ to SQL is a powerful technology that makes it simple and easy to interact with databases using object-oriented programming techniques. Modifying data using LINQ to SQL is useful when we need to update data in a specific table in the database.

Important Points

  • Any changes made to object properties are not persisted in the database until the SubmitChanges() method is called.
  • Changes made to multiple objects can be saved together by calling SubmitChanges() once at the end.

Summary

In this tutorial, we learned how to modify database data using LINQ to SQL. We saw the syntax and basic example along with explanations, and use cases. LINQ to SQL provides a simple and easy way to modify database data using object-oriented programming techniques, which makes the code more readable and maintainable.

Published on: