Archive for category LINQ

Easy Data-loading with LINQ-to-SQL and LINQ-to-XML

.Net 3.5 had some nice tricks in it. LINQ-to-XML was one of them. With the new "X"-types, you can make working with XML really easy.

VB.Net 9 takes it one step further, and lets you write XML in your code without strings.

"Hey Rich, that’s old news," I hear you say. "And who’s interested in VB today anyway?"

Well, apparently there are a lot of VB-er’s still out there. I am mainly a C# developer myself, but I found that VB was perfect for a problem I had recently -  loading of XML data into a SQL Server table.

Read the rest of this entry »

, , , , ,


Design Guidelines for LINQ

Have you wondered if and when you should use the new LINQ features in .Net 3.5?

Like, where should I put a new extension method? Should I use Func<T> or a custom delegate? How do I best implement a mix-in (extension methods on an interface)?

Well, Mircea Trofin has just published a new draft of some LINQ design guidelines. You might just find your answers there.

, ,

No Comments


I just read a fantastic quote about LINQ from the book Pro LINQ: Language Integrated Query in C# 2008 by Joseph C. Rattz, Jr.:

I prefer to think of LINQ as a data iteration engine, but perhaps Microsoft didn’t want a technology named DIE.

I think they already built the technology for such a product, and put it in Vista. 🙂

It’s a great book. The first LINQ book I’ve found with a really detailed explanation of LINQ-to-SQL and the SQLMetal generation tool.

, ,

No Comments

The LinqDataSource and the Hidden Viewstate

Yesterday I thought I’d learn about the LinqDataSource in ASP.Net 3.5, and got an interesting surprise.

The new LinqDataSource can also be used with a LINQ-to-SQL model to perform updates. You simply add the DataSource to your page, set the table name, and set EnableUpdate to true. Then, using a standard DataControl, you can make updates to your data entities.

The question is, how does this work? It appears to be a bit magical. Read the rest of this entry »

, , ,


How to Update Data with LINQ-to-SQL

When learning LINQ-to-SQL, it’s not immediately obvious how to do an update. Querying is easy, and there are methods for inserting and deleting. Updating usually occurs by modifying an object already known to the DataContext and then calling SubmitChanges on the context.

var product = (from p in dataContext.Products
               where p.ProductID == 1
               select p).Single();

product.Name = "Richard's product";


It’s nice to see that MSDN documentation actually addresses the obvious arising question:

Q. Can I update table data without first querying the database?

A. Although LINQ to SQL does not have set-based update commands, you can use either of the following techniques to update without first querying:

  • Use ExecuteCommand to send SQL code.
  • Create a new instance of the object and initialize all the current values (fields) that affect the update. Then attach the object to the DataContext by using Attach and modify the field you want to change.

Read the rest of this entry »



How to See the SQL Generated by a LINQ to SQL Command

Quick tip: If you want to see the SQL generated by LINQ to SQL for a query or command, simply set the Log property of your generated DataContext class to an instance of a TextReader.

If this is your code:

using System;
using System.Linq;
using System.Data.Linq;

namespace LINQtoSQLConsole {
  class Program {
    static void Main(string[] args) {

      var db = new NorthwindDataContext();

      // Use the console to see the SQL
      db.Log = Console.Out;

      // A query
      var cust = db.Customers.Single(
                    c => c.CustomerID == "ALFKI");

      // An update
      cust.Region = "Northwest";

… then this is what you’ll see:


Pretty good, eh?

, , ,

No Comments

How to Use Grouping in C# LINQ Syntax

When you started using LINQ, did you think it looked like SQL? I did.

The more I learned LINQ, the more I realized it wasn’t anything like SQL. Take grouping, for example. Because LINQ has a group by statement, and it looks like SQL, I assumed that the syntax for grouping in LINQ would be just like SQL. Ha ha! Wrong! As soon as I tried to use it, I discovered that the LINQ syntax is not only nothing like the SQL equivalent, but the whole grouping concept in LINQ is completely different too.

At first glance, the two syntaxes look slightly similar.


select ReportsTo, count(LastName) as NameCount
from Employees
group by ReportsTo

LINQ (C#):

from employee in Employees
group employee by employee.ReportsTo

Ignoring the omission of the select statement from LINQ, and the requirement of a range variable, they do look similar. But looks can be deceiving.

Let me explain why.

Read the rest of this entry »

, ,


LINQ to DataSets – the Missing Manual

Last week I had to prepare a small presentation for a new LINQ workshop. For my research, I browsed through the MSDN documentation on LINQ where I came across a reference to "LINQ to DataSets". I couldn’t find any more information about it though, and so LINQ to DataSets got a small mention in my presentation, but I couldn’t say anything more about it.

This morning I discovered that Fabrice Marguerie and his co-authors have published a bonus 47-page chapter of their book "LINQ in Action", all about this very subject. The chapter is called "Working with LINQ and DataSets", and they have made a PDF version available online for FREE download from the Manning Press website.

You can go get it right now.

Thanks Fabrice, for filling in the missing gap.

I’m going back to update my presentation…

, ,


Using LinqPad to Create a Time-Selector Drop-Down List

I am really getting into LINQ now! I think it’s fantastic. I recently wanted to develop a quick drop-down list in ASP.Net which allows a user to select a time of day from a list. The times are 15 minutes apart, so the list would look like this:


… and so on.

Before LINQ, I would have done this with a for loop, like this:

List<string> times = new List<string>();
for (int hour = 0; hour < 24; hour++)
  for (int minute = 0; minute < 60; minute++)
    if (minute % 15 == 0)
         "{0:00}:{1:00}", hour, minute));

That’s not difficult, although it’s not so easy to understand. I would have to write a small console app or test to make sure I had done it correct though.

I thought this might be a good opportunity to use LinqPad. It’s a great tool. You can use it to test a LINQ statement in a live window, so I thought I’d give it a go.

First I needed a LINQ statement to test.

Read the rest of this entry »

, , ,


Using Lambda Expressions with LINQ to SQL

When using LINQ, you need to be careful to use the right kind of Lambda expression. “What, there is more than one kind?”, I hear you gasp. There sure is! And if you aren’t careful, you’ll get a nice little message at runtime to tell you:

“System.Object DynamicInvoke(System.Object[])’ has no supported translation to SQL.”

What that literally means is “You’re not using lambdas right, you dummy!”

Let me explain.

Read the rest of this entry »