March, 2009

Sqlmetal.exe

Sqlmetal.exe is a handy little tool that comes with the .Net Framework 3.5 SDK — it generates code that allows you to start using Linq2Sql against your database within seconds after finishing your table scheme.

There are two great (i.e., incredibly useful) features of this tool:

  1. The generated classes are marked as partial so if you want to extend your new code, you can do so in separate files, keeping your generated file pure, untouched and able to be re-generated with a single command whenever you make data model changes.
  2. The "/serialization" option adds the [DataContract()] attribute to each class. This means that your classes can now be passed in and out of WCF operations.

SqlMetal Usage

The command I use to generated Linq2Sql classes for our "Velocity CMS" application is:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\sqlmetal.exe
/conn:"Data Source=localhost;Initial Catalog={db name};
User ID={user];Password={password}"
/code:c:\temp\vcmsdb.cs
/namespace:Vcms.Data
/pluralize /serialization:unidirectional
    

Obviously, the three elements marked with the {} must be replaced with appropriate values in order to make the command work. And, of course, you can specify the connection string elements individually with the /server, /database, and other related options.

The product of this command is found in the /code argument: c:\temp\vcmsdb.cs. This file contains my generated, Linq2Sql-ready code. Any path and filename will do here. More important, probably, is the /namespace argument, which will need to integrate nicely with your planned code base. The /pluralize argument turns words like "Item" into words like "Items" when it generates collection classes.

If need dictates, you may use the /views, /functions and /sprocs options to add views, functions and stored procedures to your generated classes.

All-in-all, sqlmetal.exe may be the most useful, time-saving and consistent tool I use in creating data access layers. In fact, sqlmetal.exe takes what use to be a time-intensive and error-prone task and makes it an absolute breeze.

 
Your feedback helps me provide content that is meaningful. Please don't be shy about speaking your mind.
Please see other tidbits.

Please provide feedback about this article

Email: (optional)