Posts tagged with linq - page 5

LINQ to SQL T4 template reloaded

A newer version of this LINQ to SQL template is available.

The topic of modifying the code generation phase of LINQ to SQL comes up quite often and the limited T4 template I published here last month was good at showing the potential but wasn’t a practical replacement for the code generation phase.

I am please to make available the next version, which now…

  • Runs from the DBML therefore keeping the designer in the loop
  • Generate all the attributes for columns and tables including UpdateCheck, IsDbGenerated etc.
  • Supports associations including those with a foreign key
  • Generates appropriate attributes and code for both serialization modes

In short it generates code that is now functionally equivalent to SQL Metal with the following caveats:

  • C# only – VB.NET can be added if there is some interest
  • Stored procedures – not yet supported
  • Table inheritance – incomplete
  • DBML changes require you open and re-save the T4 template so it regenerates the code
  • Unidirectional serialization requires you add System.Runtime.Serialization to your project references (thanks Roger!)

To use the template:

  • Extract the archive and add the two files to your project
  • Right-click on the L2ST4.tt file, choose Properties and set the Custom Tool to blank
  • Rename DataClasses1.tt to the same name as your DBML file (but keeping the .tt extension) and open it
  • Click save and watch a freshly generate C# DataContext pop out
  • Switch off the LINQ to SQL designer generated C# by either setting the Custom Tool on the DBML to blank or setting the Build Action on the generated C# to None.

L2ST4.tt contains a lightweight wrapper around the DBML which is processed using LINQ to XML making the template easier to work with and providing a central for naming rules etc.

This code should be treated as a sample and hasn’t received much testing yet so feel free to leave comments or feedback here.

Some places you could take this template:

  • Generate an interface for your data context to improve mocking
  • Alternative naming and defaults
  • Splitting output into multiple files
  • New languages

[)amien

Experimental LINQ to SQL template

A newer version of this LINQ to SQL template is available.

While SQLMetal does a good job of turning your SQL schema into a set of classes for you it doesn’t let you customize the code generation process.

Usefully there is now a templating system built into Visual Studio 2008 called Text Templates (T4 for short).

Here is a short (369 line) experimental proof-of-concept T4 template I wrote last night that will generate a data context and associated entity classes as a starting point similar to that produced by SQLMetal.

Download of this old version no longer available, see the newer article!

Once downloaded unzip and drop the DataContext.cs.tt into your project and edit line 17 to set the connection string. You can also edit lines 18 and 19 to set the namespace and class name. The lightweight wrappers around database, table and column can be found at the end of the file – they simply wrap the SQL Server Information_Schema views as briefly as possible.

Within seconds Visual Studio should have created a code-behind file for the DataContext named DataContext.cs.cs with your generated code ready to use :) If you don’t like the way the template generates your context you can change it :)

There are limitations with this experimental proof-of-concept including: </p>
  • Processes all and only tables in the database (no views or SP’s)
  • Foreign-key relationships are not implemented
  • Column attributes for IsDbGenerated, UpdateCheck and AutoSync not implemented
  • C# only (sorry Julie)
  • Plural and singular naming rules are incomplete
  • Can’t modify schema as you could with a designer stage
To learn more about T4: </p>

[)amien

Using LINQ to foreach over an enum in C#

I can’t be the only person in the world who wants to foreach over the values of an enum otherwise Enum.GetValues(Type enumType) wouldn’t exist in the framework. Alas it didn’t get any generics love in .NET 2.0 and unhelpfully returns an array.

Thanks to the power of LINQ you can do this:

foreach(var customerType in Enum.GetValues(typeof(CustomerTypes)).Cast<CustomerTypes>()))

That is okay, but this is more concise:

foreach(CustomerTypes customerType in Enums.Get<CustomerTypes>())

The tiny class to achieve that is, of course:

using System.Collections.Generic;
using System.Linq;

public static class Enums {
  public static IEnumerable<T> Get<T>() {
    return System.Enum.GetValues(typeof(T)).Cast<T>();
  }
}

Great.

[)amien

Joining the LINQ to SQL team at Microsoft

I’ve been quiet on my blog lately largely because I have been preparing to change job and relocate half-way around the world to Vancouver in the beautiful province of British Columbia (where I spent my 2004 summer holiday).

In February I traveled out to Redmond for three days of interviews (one position grew to two, then three). Having read the Microsoft Jobs Blog I was prepared for long hard days but in reality the process was incredibly enjoyable and exciting.

So much so I wanted to find a desk and move in right then.

With some luck I also found myself at Hanselman’s geek dinner which involved some great discussions and the chance to meet Scott himself, Brad Wilson and Nikhil Kothari who I knew from .NET on-line community as well as some ~35 other developers from both within Microsoft and the outside world. It was one fun evening and my thanks go to Scott for kindly driving me back to my hotel in Redmond town center.

Many white-boards and a few lunches later (including an unexpected one with Phil Haack, Nikhil and two more guys from ASP.NET team – I wish I could remember all the names of the people I met!) I found myself with the hard task of choosing a position.

I settled on a developer role within the LINQ to SQL team starting mid-May and am counting down the days…

[)amien