Click here to Skip to main content
12,896,953 members (48,332 online)
Click here to Skip to main content
Add your own
alternative version


43 bookmarked
Posted 19 Apr 2009

Using SQLMetal code generator tool for LINQ to SQL

, 20 Apr 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Using SQLMetal code generator tool for LINQ to SQL


An OR mapper release from MS was long over due and I'm sure some/most of you have already explored LINQ.

So what is SQLMetal?

It's a code generation tool built by Microsoft to aid in LINQ based development. The tool simply builds code and mapping  that you would otherwise have to code by hand. Unless you had access to the Visual Studio 2008 IDE. Even then its a matter of dragging and dropping tables and other Database objects into the LINQ to SQL environment.  Also when working in a development team,  database changes made by a DBA or other developers will need to be incorporated in your development environment. You would need to delete and recreate each database object in the LINQ to SQL environment every time they changes are made. Needless to say this would become an unnecessarily tedious task to perform. But with SQLMetal you could generate and distribute the dbml file every time changes are made. It can also be included as part of an automated build, as it is a command line tool.

Please note that I have illustrated just one method of using SQLMetal in this article. There are several other ways of using it.


SQLMetal works as a command line tool that accepts a bunch of parameter options such as database connection parameters and outputs mapping or code files. You would then use this code file within your development environment with LINQ code for accessing and manipulating data in the database. Note SQLMetal generates one file with all code or mappings.


The tool is located under the following directory

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\SqlMetal.exe

How to use the tool  

1. If you are using Visual studio, create a web project E.g : NorthWind. Then add a folder called DAL.

2. Create an empty folder for SQLMetal output file E.g : C:\MyProject

3. Then open a Command Window and navigate to the directory (see location) where SqlMetal is located.

4. Then use the following command for generating a single file called NorthWind.dbml.

SqlMetal.exe /server:localhost /database:NorthWind /dbml:C:\MyProject\DAL\NorthWind.dbml /namespace:NorthWind.DAL<br />/Context:NorthWindDataContext /provider:SQL2005 /pluralize

* To stick with the MS naming convention I have appended "DataContext" to the name of my DataContext class, this helps identify it as a DataContext object. However you can call it what ever you want.
* I have created a separate folder E.G: DAL for the auto generated code, this ensures better management of your code.
* I use the pluralize option when generating the code, as it makes naming enumeration objects easy to write and comprehend.

Using the auto generated code. 

If you are using Visual studio, you will need to add the NorthWind.dbml in the DAL folder. To do this Right click the DAL folder under your project in solution explorer, then click on add then on Existing Item navigate to DAL folder or where ever else you have generated the output file and include it in the project.

First we need to create a connection string, for all practical reasons its good to do so in the web config.

  <add name="NorthwindConnectionString" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True"
  providerName="System.Data.SqlClient" />
You can declare a string variable and use the ConfigurationManager to get the connection string values from the web config
string connStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
Instantiate an Object of the NorthWindDataContext class and write your LINQ query
NorthWind.DAL.NorthWindDataContext db = new NorthWind.DAL.NorthWindDataContext(connStr);
var cust = from c in db.Customers  select c;
You can then use the data in anyway that you wish, I have used it here to bind to a GirdView control.
gv.DataSource = cust;
* If you have to extend the DataContext object I would recommend you write wrapper classes to do so rather than hack the auto generated code as you may need to regenerate the code several times during development.

Improving productivity

You can store the command line execution in a batch file. This will help you regenerate code with a single click every time there are changes made to the DataBase. I have included a batch file in the download file.

* I am assuming you will deploy this under C: see batch file. If not please make appropriate changes to the batch file.

Complete list of options and usage for SQLMetal 

SqlMetal [options] [<input file>]

  - Generates code and mapping for the LINQ to SQL component of the .NET framework. SqlMetal can:
  - Generate source code and mapping attributes or a mapping file from a database.
  - Generate an intermediate dbml file for customization from the database.
  - Generate code and mapping attributes or mapping file from a dbml file.


  /server:<name>                   Database server name.
  /database:<name>               Database catalog on server.
  /user:<name>                      Login user ID (default: use Windows Authentication).
  /password:<password>          Login password (default: use Windows Authentication).
  /conn:<connection string>     Database connection string. Cannot be used with /server, /database, /user or /password options.
  /timeout:<seconds>              Timeout value to use when SqlMetal accesses the database (default: 0 which means infinite).

  /views                                Extract database views.
  /functions                           Extract database functions.
  /sprocs                               Extract stored procedures.

  /dbml[:file]                          Output as dbml. Cannot be used with /map option.
  /code[:file]                          Output as source code. Cannot be used with /dbml option.
  /map[:file]                           Generate mapping file, not attributes. Cannot be used with /dbml option.

  /language:<language>           Language for source code: VB or C# (default: derived from extension on code file name).
  /namespace:<name>              Namespace of generated code (default: no namespace).
  /context:<type>                    Name of data context class (default: derived from database name).
  /entitybase:<type>                Base class of entity classes in the generated code (default: entities have no base class).
  /pluralize                              Automatically pluralize or singularize class and member names using English language rules.
  /serialization:<option>            Generate serializable classes: None or Unidirectional (default: None).
  /provider:<type>                   Provider type: SQLCompact, SQL2000, or SQL2005. (default: provider is determined at run time).

  <input file>                           May be a SqlExpress mdf file, a SqlCE sdf file, or a dbml intermediate file.

Create code from SqlServer:
  SqlMetal /server:myserver /database:northwind /code:nwind.cs /namespace:nwind

Generate intermediate dbml file from SqlServer:
  SqlMetal /server:myserver /database:northwind /dbml:northwind.dbml /namespace:nwind

Generate code with external mapping from dbml:
  SqlMetal /code:nwind.cs / northwind.dbml

Generate dbml from a SqlCE sdf file:
  SqlMetal /dbml:northwind.dbml northwind.sdf

Generate dbml from SqlExpress local server:
  SqlMetal /server:.\sqlexpress /database:northwind /dbml:northwind.dbml

Generate dbml by using a connection string in the command line:
  SqlMetal /conn:"server='myserver'; database='northwind'" /dbml:northwind.dbml

Points of Interest 

Since it is a command line tool it can be used in your build file/process.

Sadly there is no support for maintaining version history of the automated code but you can over come this by integrating output with a code repository see the batch file included in the download.  


The sample Northwind database doesn't ship with SQL2005 you can get it from here.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ritesh Ramesh
Architect Infosolvex Solutions Inc
Australia Australia
Ritesh is an IT consultant with over ten years of experience in the IT industry varying from consultation, architecture, design, development to technical management. He has a strong background in solutions and applications architecture with a focus on Microsoft’s .Net platform. His area of expertise spans design and implementation of client/server, database and web-based systems. He has worked with C#, ASP.NET 1.1 and 2.0, ADO.NET, Web Services and SQL technology on several enterprise class projects.

Freedom is not worth having if it does not include the freedom to make mistakes.
Mahatma Gandhi

You may also be interested in...


Comments and Discussions

GeneralHi Ramesh Pin
BMS201111-Apr-12 0:05
memberBMS201111-Apr-12 0:05 
GeneralInclude only specific stored procedures in dbml Pin
PiyushVarma21-Jan-11 7:51
memberPiyushVarma21-Jan-11 7:51 
GeneralCannot resolve moniker Pin
bluetx5-Jun-09 1:36
memberbluetx5-Jun-09 1:36 
GeneralLink to Northwind Pin
Richard MacCutchan21-Apr-09 3:46
memberRichard MacCutchan21-Apr-09 3:46 
GeneralRe: Link to Northwind Pin
Ritesh Ramesh21-Apr-09 9:30
memberRitesh Ramesh21-Apr-09 9:30 
GeneralRe: Link to Northwind Pin
Richard MacCutchan22-Apr-09 1:07
memberRichard MacCutchan22-Apr-09 1:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170424.1 | Last Updated 20 Apr 2009
Article Copyright 2009 by Ritesh Ramesh
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid