In this comprehensive guide, I’ll cover everything you need to know about LINQ to SQL, from basic concepts to practical implementations that you can start using today.
Released with .NET Framework 3.0, LINQ to SQL is Microsoft’s technology that bridges the gap between relational databases and object-oriented programming. It eliminates the need to write traditional SQL queries by providing a way to query databases directly from C# code.
The beauty of LINQ to SQL is that it’s not limited to just SQL databases—you can use similar syntax to query arrays, lists, XML documents, and more. But in this tutorial, we’re focusing specifically on using LINQ with SQL Server databases.
Note: If you are starting out, the LinQ Tutorials Series might just be what you are looking for!
To use LINQ to SQL, you’ll need:
Let’s dive right into setting up your project!
First, we need to create a mapping between our database tables and .NET classes:
This creates a .dbml file with a visual designer that has two parts:
Now, let’s map our database tables:
The designer will generate classes that represent your tables, with properties matching your table columns. If your table name is plural (like “Users”), LINQ typically creates a singular class name (“User”), though the table reference in queries will remain plural.
Now for the fun part—writing queries! Here are some common scenarios you’ll encounter:
Let’s start with validating a user against a username and password:
public bool IsValidUser(string userName, string password)
{
    MyDatabaseDataContext db = new MyDatabaseDataContext();
    
    var userResults = from u in db.Users
                      where u.Username == userName && u.Password == password
                      select u;
    
    return userResults.Count() > 0;
}Code language: JavaScript (javascript) Notice how similar this is to SQL syntax, yet it’s integrated directly into C#! The query returns a collection of User objects that match our criteria.
If you prefer a more method-oriented approach, you can achieve the same result using extension methods:
public bool IsValidUser(string userName, string password)
{
    MyDatabaseDataContext db = new MyDatabaseDataContext();
    
    var users = db.Users.Where(u => u.Username == userName && u.Password == password);
    
    return users.Count() > 0;
    
    // Even more concise:
    // return db.Users.Any(u => u.Username == userName && u.Password == password);
}Code language: JavaScript (javascript) Both approaches are valid—choose the one that feels more natural to you!
When you need just one record, the Single() or SingleOrDefault() methods are perfect:
public User GetUser(string userName)
{
    MyDatabaseDataContext db = new MyDatabaseDataContext();
    
    // Returns exactly one user or throws exception if not found
    User user = db.Users.Single(u => u.Username == userName);
    
    // Alternatively, returns null if not found:
    // User user = db.Users.SingleOrDefault(u => u.Username == userName);
    
    return user;
}Code language: JavaScript (javascript) When dealing with multiple records, a foreach loop makes it easy to process each result:
public List<string> GetAdminEmails()
{
    MyDatabaseDataContext db = new MyDatabaseDataContext();
    var admins = from u in db.Users
                 where u.Role == "admin"
                 select u;
    
    List<string> adminEmails = new List<string>();
    
    foreach (User admin in admins)
    {
        adminEmails.Add(admin.Email);
    }
    
    return adminEmails;
}Code language: PHP (php) As with any technology, there are some gotchas to be aware of:
LINQ queries aren’t executed when you define them—they run when you enumerate the results:
// Query is defined here but NOT executed yet
var expensiveProducts = from p in db.Products
                        where p.Price > 100
                        select p;
// Now the query executes when we iterate through results
foreach (var product in expensiveProducts)
{
    Console.WriteLine(product.Name);
}Code language: JavaScript (javascript) This is powerful, but can cause confusion if you’re not aware of it!
Be careful with nested queries that might result in multiple database hits:
// This could result in many database queries
foreach (var customer in db.Customers)
{
    // This executes a separate query for EACH customer!
    foreach (var order in customer.Orders)
    {
        // Process order
    }
}Code language: PHP (php) Instead, use eager loading with LoadWith:
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Customer>(c => c.Orders);
db.LoadOptions = options;
// Now this executes just ONE query that includes orders
foreach (var customer in db.Customers)
{
    foreach (var order in customer.Orders)
    {
        // Process order
    }
}Code language: PHP (php) After making changes to your entities, don’t forget to call SubmitChanges() to save them to the database!
To get the most out of LINQ to SQL:
Take() and Skip() for pagination.While LINQ to SQL is powerful, Microsoft has focused more development on Entity Framework in recent years. Consider Entity Framework when:
However, LINQ to SQL remains excellent for simpler applications and is often easier to learn for beginners.
LINQ to SQL completely transforms how you interact with databases in C#. It bridges the gap between object-oriented programming and relational databases, making your code cleaner, safer, and more maintainable.
Start small with basic queries, then gradually explore more advanced features as you get comfortable. The type safety and IntelliSense support will catch many errors before they happen, making development faster and less frustrating.
I hope this guide helps you get started with LINQ to SQL! If you have questions or need more examples, feel free to ask in the comments below.
Happy coding! 🚀
Learn python file handling from scratch! This comprehensive guide walks you through reading, writing, and managing files in Python with real-world examples, troubleshooting tips, and…
You've conquered the service worker lifecycle, mastered caching strategies, and explored advanced features. Now it's time to lock down your implementation with battle-tested service worker…
Unlock the full potential of service workers with advanced features like push notifications, background sync, and performance optimization techniques that transform your web app into…
This website uses cookies.
View Comments
Thank you for the short tutorial. It's very helpful.
Keep up the good work! very good tutorial, i help me a lot
Rana
Very clear and simple, very helpful. Thank you !
Really good attempt..... It hepl a lot,.
I would like to use a sql view to get the data instead of a table in c#. How I can do it? Thanks.
I didn't get your point. Can you please explain a little more?
Simply drag the view onto the (left part of the) designer instead of the table. That should do the trick.
br johannes
excellent descrption
i need to use sql tables and sp's witout adding it in SqltoClasses. It is possible using only dbContext.
Excellent
Really helpful ! It helps me a lot to getting basic of Linq. Thanks again
Hello sir, you have not mention where i have write the above code after add table in linq
Wherever you add it, doesn't matter, as long as you have its namespace added to your .cs file you are writing.