LINQ to SQL (Language Integrated Query to SQL) is a component of the .NET Framework that allows developers to work with relational data using the same syntax and tools they use for querying objects. It provides a way to query, insert, update, and delete data in a database using C# or Visual Basic.
In this tutorial, we will explore how to use LINQ to SQL to interact with databases. We'll cover basic querying, as well as more advanced operations like filtering, sorting, and joining data.
LINQ to SQL is built on top of the .NET Framework's LINQ (Language Integrated Query) technology. It allows developers to write queries in a strongly-typed manner using C# or Visual Basic. The queries are translated into SQL commands that are executed against the database.
The main components of LINQ to SQL include:
Before we start querying data, we need to set up our project. Here are the steps:
DataClasses.dbml.Let's start by querying data from a table. Assume we have a Customers table with columns like CustomerID, CompanyName, and ContactName.
using System;
using System.Linq;
using DataClasses; // Namespace generated by LINQ to SQL
class Program
{
static void Main()
{
// Create a new DataContext instance
using (var db = new NorthwindDataContext())
{
// Query all customers
var customers = from customer in db.Customers
select customer;
// Display the results
foreach (var customer in customers)
{
Console.WriteLine($"{customer.CustomerID}: {customer.CompanyName}");
}
}
}
}
You can filter data using LINQ's Where method. For example, to find all customers from a specific country:
using System;
using System.Linq;
using DataClasses;
class Program
{
static void Main()
{
using (var db = new NorthwindDataContext())
{
// Query customers from Germany
var germanCustomers = from customer in db.Customers
where customer.Country == "Germany"
select customer;
foreach (var customer in germanCustomers)
{
Console.WriteLine($"{customer.CustomerID}: {customer.CompanyName}");
}
}
}
}
You can sort data using LINQ's OrderBy or OrderByDescending methods. For example, to sort customers by company name:
using System;
using System.Linq;
using DataClasses;
class Program
{
static void Main()
{
using (var db = new NorthwindDataContext())
{
// Query and sort customers by CompanyName
var sortedCustomers = from customer in db.Customers
orderby customer.CompanyName
select customer;
foreach (var customer in sortedCustomers)
{
Console.WriteLine($"{customer.CustomerID}: {customer.CompanyName}");
}
}
}
}
You can join tables using LINQ's Join method. For example, to join the Customers table with the Orders table:
using System;
using System.Linq;
using DataClasses;
class Program
{
static void Main()
{
using (var db = new NorthwindDataContext())
{
// Join Customers and Orders tables
var customerOrders = from customer in db.Customers
join order in db.Orders on customer.CustomerID equals order.CustomerID
select new { CustomerName = customer.CompanyName, OrderID = order.OrderID };
foreach (var item in customerOrders)
{
Console.WriteLine($"{item.CustomerName}: Order ID {item.OrderID}");
}
}
}
}
To insert data into the database, you can create a new entity object and add it to the Table<T> collection:
using System;
using DataClasses;
class Program
{
static void Main()
{
using (var db = new NorthwindDataContext())
{
// Create a new customer
var newCustomer = new Customer
{
CustomerID = "CUST101",
CompanyName = "New Customer Co.",
ContactName = "John Doe"
};
// Add the new customer to the Customers table
db.Customers.InsertOnSubmit(newCustomer);
// Submit changes to the database
db.SubmitChanges();
Console.WriteLine("Customer added successfully.");
}
}
}
To update data, you can modify the properties of an entity object and then call SubmitChanges:
using System;
using DataClasses;
class Program
{
static void Main()
{
using (var db = new NorthwindDataContext())
{
// Find a customer by CustomerID
var customer = (from c in db.Customers
where c.CustomerID == "CUST101"
select c).FirstOrDefault();
if (customer != null)
{
// Update the contact name
customer.ContactName = "Jane Doe";
// Submit changes to the database
db.SubmitChanges();
Console.WriteLine("Customer updated successfully.");
}
}
}
}
To delete data, you can remove an entity object from the Table<T> collection and then call SubmitChanges:
using System;
using DataClasses;
class Program
{
static void Main()
{
using (var db = new NorthwindDataContext())
{
// Find a customer by CustomerID
var customer = (from c in db.Customers
where c.CustomerID == "CUST101"
select c).FirstOrDefault();
if (customer != null)
{
// Remove the customer from the Customers table
db.Customers.DeleteOnSubmit(customer);
// Submit changes to the database
db.SubmitChanges();
Console.WriteLine("Customer deleted successfully.");
}
}
}
}
In this tutorial, we covered the basics of querying and manipulating data with LINQ to SQL. In the next section, we will explore Async Programming in C#, which allows you to write asynchronous code that can improve the performance of your applications by not blocking the main thread while waiting for I/O operations to complete.
Stay tuned for more advanced topics and practical examples!