LINQ to SQL
LINQ to SQL is a component of the .NET Framework that provides a run-time infrastructure for managing relational data in a SQL Server database. It enables developers to query relational data by using the Language Integrated Query (LINQ) syntax. LINQ to SQL translates LINQ queries into SQL statements, executes them against the database, and returns results as objects.
- Object-Relational Mapping (ORM)
- LINQ query syntax for data access
- Automatic SQL generation
- Support for stored procedures
- Change tracking and persistence
Getting Started with LINQ to SQL
To use LINQ to SQL, you typically define your database schema in a .dbml
file using the Object Relational Designer in Visual Studio. This designer generates C# or Visual Basic code that represents your database tables as C# classes and relationships as properties. You can then use these classes to query your database.
Here's a simple example of querying data:
using System;
using System.Linq;
using MyDatabaseNamespace; // Assuming your generated classes are here
public class DataAccessExample
{
public static void Main(string[] args)
{
// Replace "NorthwindDataContext" with your actual DataContext class name
using (NorthwindDataContext db = new NorthwindDataContext())
{
// Query for customers in London
var londonCustomers = from cust in db.Customers
where cust.City == "London"
select cust;
Console.WriteLine("Customers in London:");
foreach (var customer in londonCustomers)
{
Console.WriteLine($"- {customer.ContactName} ({customer.CustomerID})");
}
}
}
}
Core Concepts
-
DataContext: The primary class that represents your database connection. It is generated from your
.dbml
file and provides access to your tables and stored procedures. - Entity Classes: C# classes that map to database tables. Each property of the class typically maps to a column in the table.
- Querying: You can write queries using LINQ syntax directly against your entity classes. LINQ to SQL translates these queries into efficient SQL.
-
Submitting Changes: After modifying objects, you call
db.SubmitChanges()
to send the changes back to the database.
Advantages of LINQ to SQL
- Reduces boilerplate data access code.
- Improves developer productivity by allowing queries in a strongly typed language.
- Provides a clean separation between the data layer and business logic.