Back to all posts
C#.NETLINQSQL

Using LINQ to SQL Template – Part One

SathishMarch 10, 2010

LINQ to SQL is an ORM (Object Relational Mapping) framework that allows you to work with databases using LINQ queries.

Setting Up LINQ to SQL

  • Add a new LINQ to SQL Classes item to your project (.dbml file)
  • Drag tables from Server Explorer onto the designer
  • The designer generates entity classes automatically

Basic Queries

csharp
using (DataContext db = new DataContext(connectionString))
{
    // Simple select
    var customers = from c in db.Customers
                    select c;
    
    // With where clause
    var filteredCustomers = from c in db.Customers
                            where c.City == "Sydney"
                            select c;
    
    // With ordering
    var orderedCustomers = from c in db.Customers
                           orderby c.Name ascending
                           select c;
    
    // Selecting specific columns
    var names = from c in db.Customers
                select new { c.Name, c.Email };
}

Method Syntax

csharp
var customers = db.Customers
    .Where(c => c.City == "Sydney")
    .OrderBy(c => c.Name)
    .Select(c => new { c.Name, c.Email });

Continue to Part Two for advanced queries and data manipulation.

0claps
Share this post

Comments

Protected by reCAPTCHA v3

No comments yet. Be the first to comment.