Back to all posts
C#.NETLINQSQL

Using LINQ to SQL Template – Part Two

SathishMarch 12, 2010

This is the continuation of Part One of the LINQ to SQL tutorial.

Advanced Queries

csharp
// Join example
var query = from c in db.Customers
            join o in db.Orders on c.CustomerID equals o.CustomerID
            select new { c.Name, o.OrderDate, o.Total };

// Group by example
var grouped = from o in db.Orders
              group o by o.CustomerID into g
              select new { CustomerID = g.Key, TotalOrders = g.Count() };

// Aggregate functions
var stats = from o in db.Orders
            group o by o.CustomerID into g
            select new {
                CustomerID = g.Key,
                TotalAmount = g.Sum(x => x.Total),
                AverageAmount = g.Average(x => x.Total),
                MaxOrder = g.Max(x => x.Total)
            };

Data Manipulation

csharp
// Insert
Customer newCustomer = new Customer { Name = "John", Email = "[email protected]" };
db.Customers.InsertOnSubmit(newCustomer);
db.SubmitChanges();

// Update
var customer = db.Customers.First(c => c.CustomerID == 1);
customer.Name = "Updated Name";
db.SubmitChanges();

// Delete
var toDelete = db.Customers.First(c => c.CustomerID == 1);
db.Customers.DeleteOnSubmit(toDelete);
db.SubmitChanges();
0claps
Share this post

Comments

Protected by reCAPTCHA v3

No comments yet. Be the first to comment.