Skip to content

T4 Toolbox Offers Alternate LINQ to SQL Class Generator: Explained & What It Can Do For You

If you aren’t up with the know, T4 Templates or the Text Template Transformation Toolkit is a Microsoft template-driven code generation toolkit baked right into Visual Studio 2008 (and available in Visual Studio 2005 as an additional download) which allows you to do some pretty cool stuff in the way of code generation — that being generating classes, sql scripts, MVC and/or Dynamic Data templates, or anything you like really.  It can plug in and read database information quickly and has gained a lot more traction over the last year or so with the adoption by ASP.NET MVC and Dynamic Data really driving it’s name, however unfortunately with the lack of great IDE support, which I’m hoping might change a little come Visual Studio 2010 there is no in-built syntax highlighting or easy way to get started with using it (eg. no “Add new item”).  However, it’s a great system and can provide loads of benefit out of the box. (If you would like further reading on the subject, check out Scott Hanselman’s article on the topic posted last year).

Whilst I love the concept of T4, I didn’t write this to discuss that, but rather a community developed tool entitled the T4 Toolbox and specifically their LINQ to SQL Classes Generator template they have designed.  But first a little background on the T4 Toolbox from Oleg Sych’s blog (the primary developer of this tool):

T4 Toolbox is a set of ready-to-use code generation templates and essential supporting tools like custom directive processors, packaged in a simple installation program. Each completed code generation template includes a Visual Studio project item template to make it available in the Add New Item dialog of Visual Studio.

So what’s the “LINQ to SQL Classes Generator” I speak about then?  Well it’s a component built off the toolbox which offers you an alternate method in generating your LINQ to SQL classes from the traditional MSLinqToSqlGenerator which is the actual process behind the scenes which generates your LINQ to SQL classes normally — fundamentally it will achieve the same thing, that being you receive a set of LINQ to SQL classes and a .dbml to work with, but delivering it in a more enhanced, layered-out and more cohesive pattern over the default single-file .dbml behemoth you typically get.

I will let Oleg explain:

Build 9.1.20.1 of T4 Toolbox includes a new, ready-to-use code generator that produces LINQ to SQL classes in C#. This generator uses .dbml file produced by the standard LINQ to SQL designer in Visual Studio and can be used as an alternative to the standard MSLinqToSqlGenerator.

You may be wondering why do we need yet another LINQ to SQL code generator, especially now that ADO.NET team placed it in maintenance mode in favor of the Entity Framework. Even though the Entity Framework may be more flexible and powerful, LINQ to SQL is currently the only data access framework built into .NET Framework and Visual Studio that allows modeling and generating both database and application code. LINQ to SQL strikes a good balance between simplicity and power, making it a great fit for a large class of business applications. Simplicity of modeling both database and application code makes it superior to Entity Framework on smaller projects that don’t require advanced O/R mapping or don’t need to access different types of data sources.

However, built-in code generation tools, SqlMetaL and MSLinqToSqlGenerator, have several limitations that make it difficult to scale LINQ to SQL solutions beyond the simplest scenarios. In particular, the application code is generated in a single file, which can reach size of tens of thousands lines of code for medium-sized databases and hundreds of thousands lines of code for large-size databases. The other limitation is the lack of direct generation of database source code. You can use CreateDatabase method of DataContext class to create a database based on a LINQ to SQL model. However, you will need to reverse engineer this database into another database tool, such as Visual Studio Database Edition or Enterprise Architect in order to model, maintain and evolve a database on a non-trivial project.

The code generator described in this article addresses the first limitation of LINQ to SQL by splitting generated DataContext and entity classes into separate .cs files. These files are a lot smaller and easier to work with than the monolithic designer.cs file produced by standard tools. The second limitation of not generating database code directly will be addressed by another code generator called “LINQ to SQL Schema”, which is still under development. Together, these two code generators will enable true model-driven development approach for LINQ to SQL solutions.

However since that was written, the team then introduced in May 2009 the “LINQ to SQL Schema” available right now. This is great for those who have always wanted to be able to develop from a “model up” approach but couldn’t, whereby you create/make changes to your application model in .NET, and have those changes reflect on your database schema, rather than upkeeping the two separately. Also loads more benefits if you are a VS Database Edition or Enterprise Architecture Edition user. A short quote below explains:

Build 9.5 of T4 Toolbox extends the LINQ to SQL generator introduced in version 9.1 with support for database schema generation. This gives you the ability to generate both application code, such as entity and data context classes, and database code, such as table, primary and foreign key scripts, from a single LINQ to SQL dbml file in your solution. Generated database scripts can be automatically added to a VSTS Database project, which will automatically handle majority of database deployment issues by automatically generating the ALTER scripts. In other words, combined with VSTS Database edition, T4 Toolbox allows you to use model-driven or model-first approach for ongoing development of LINQ to SQL applications.

Some of the important differences between the LINQ to SQL Class Generator and that generated by the MSLinqToSqlGenerator are:

  • While MSLinqToSqlGenerator uses fully-qualified, global:: type names, this template produces code with “using” directives and abbreviated names. This is done to make the generated code easier to read.
  • While MSLinqToSqlGenerator generates field names as property name with an underscore prefix, this method simply converts the property name to camelCase. This is done for consistency with the StyleCop rule SA1306: Variable names must start with a lower-case letter.
  • While MSLinqToSqlGenerator assumes that unknown data types are reference types this method assumes that unknown types are value types. Assuming that users will mostly use built-in types or known CLR types in the model, the most frequently used custom types will be enumerations. Treating unknown types as value types allows us to generate nullable enum types when model defines a nullable property.
  • While MSLinqToSqlGenerator always emits InheritanceMapping attributes with inheritance code values enclosed in double quotation marks, making them strings, this generator emits them verbatim, preserving the original data type. This allows using enum values as inheritance code directly, without the need to convert. User can still use string values by enclosing them in double quotation marks in the model/designer.
  • While MSLinqToSqlGenerator produces entity code that fires PropertyChanging event with empty property name, this template produces code fires PropertyChanging events with actual property names.
  • While MSLinqToSqlGenerator produces a DataContext code that always uses an empty, explicitly created AttributeMappingSource in constructors that don’t receive mappingSource as a parameter, this generator simply calls the matching base constructor.
  • Generation of method wrappers for stored procedures and functions is not supported at this time

So all this sounds pretty cool and no doubt you will want to get started straight away to see how it can benefit you.

I think it’s important to note that Oleg states that the T4 templates T4 Toolbox use are stored in C:\Program Files\T4 Toolbox\T4Toolbox\LinqToSql by default so perhaps if there is something you don’t like about the template, or you require additional functionality, such as a standard implementation all your entites derive from, it could be changed in the appropriate .tt file.

RESOURCES:

Remember, this article focusses primarily on the LINQ to SQL Class Generator provided by the T4 Toolbox, but there is tons of other great stuff the T4 Toolbox offers which is all layed out on Codeplex.

Thanks for the great stuff Oleg and Team!

VN:F [1.9.10_1130]
Rating: 4.7/5 (3 votes cast)
VN:F [1.9.10_1130]
Rating: +2 (from 2 votes)
T4 Toolbox Offers Alternate LINQ to SQL Class Generator: Explained & What It Can Do For You, 4.7 out of 5 based on 3 ratings
Bookmark and Share
kick it on DotNetKicks.com
Shout it

NOW, FOR A WORD FROM OUR SPONSORS

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*

My name is Graham O'Neale and I'm a software architect from Gold Coast, Australia. I am an overtime thinker, full time coder and awake part time in the real world. I have a keen interest in software development, particularly in the realm of programming (C#, ASP.NET, ASP.NET MVC, LINQ (2 SQL), Entity Framework, Silverlight, Blend, WCF, WPF) and a keen interest in the cutting edge and innovation. I have a new found love for design patterns, ALT.NET practices and well crafted software architecture. The purpose of this blog is to express any thoughts, findings, tips and gripes along my travels in the wonderful world of coding and technology...