Monday, March 31, 2008

...and I found SqlMetal.exe on my machine...

I was reading the online version of the SQL Server Magazine April 2008 edition when I chanced upon an article on LINQ which talks about this tool. This is the first time I've read about this tool so I read further. SqlMetal.exe is a command-line tool that generates code and mapping for the LINQ to SQL component of the .NET Framework. When I started working with LINQ, I was only using Visual Studio 2008 to generate the object-relational diagram by dragging-and dropping the database objects on my designer surface. You can find this tool inside the \Program Files\Microsoft SDKs\Windows\v6.0a\bin folder. It generates the necessary data entity and DataContext object for LINQ as either a .vb or .cs source file. You can run this tool using the Visual Studio 2008 Command-Prompt or navigating to the folder location using command prompt and execute from there. A sample code to use SqlMetal.exe is shown below

sqlmetal /server:localhost /database:Northwind /language:cs /code:Northwind.cs

The command generates a .cs file from the Northwind database running on my SQL Server 2000 instance. When you open the code in Visual Studio 2008, you will see the codes which may seem familiar if you have used the designer to create LINQ objects. The code includes all the database entities and their corresponding attributes, meaning the tables and their fileds with constraints and data types. If you need to include stored procedures and functions, you can simply add the /sprocs and /functions switches. If you're thinking of simply ignoring this tool since the designer is already available for you, think again. It only took me like 10 seconds to type the syntax and it generated the code for me. Compare that to using the designer and dragging and dropping the database objects which would take me at least a minute or two. This would be a great time saver if you need to generate codes for about 50 databases scattered in different SQL Server instances in your environment. Cool tool for developers
Google