Very short and simple example of using SqlMetal
A simple sample of how to use SqlMetal.
"Code Generation Tool (SqlMetal.exe)"
https://msdn.microsoft.com/en-us/library/bb386987.aspx
This tool will create mappings and code for LINQ to SQL.
So, as mentioned, simple and short. Create a database, some tables and insert some data.
create database VeryMetal
go
use VeryMetal
go
create table Users (UserId int primary key, FirstName nvarchar(10), LastName nvarchar(10), DepartmentId int)
go
create table Departments(DepartmentId int primary key, DepartmentName nvarchar(10))
go
--Insert some users and departments
insert into Users values (1, 'John', 'Johnson', 1)
insert into Users values (2, 'Paul', 'Paulson', 2)
insert into Users values (3, 'Mike', 'Mikeson', 1)
insert into Users values (4, 'Mary', 'Maryson', 2)
insert into Departments values (1, 'Support')
insert into Departments values (2, 'Finance')
Then fire up the Visual Studio Command Prompt and run the following:
Sqlmetal /server:<your server> /database:VeryMetal /code:C:\Temp\MetalCode.cs /map:C:\Temp\MetalMap.xml /namespace:VeryMetalEntities
This should now have generated the .cs and .xml files.
So, create new console application, add the MetalCode file to the project and enter the following code:
static void Main(string[] args)
{
try
{
String cs = @"Data Source=<your server>;Initial Catalog=VeryMetal;Integrated Security=True";
String file = @"C:\Temp\MetalMap.xml";
var dc = new VeryMetal(cs, XmlMappingSource.FromUrl(file));
var users = from u in dc.Users where u.DepartmentId == 1 select u;
Console.WriteLine("All users in Support Department.");
foreach (var user in users)
{
Console.WriteLine("{0} - {1}", user.FirstName, user.LastName);
}
Console.WriteLine("\nGet single user with firstname starting with Pau ");
Table<Users> ut = dc.GetTable<Users>();
var users2 = ut.Single(x => x.FirstName.StartsWith("Pau"));
Console.WriteLine("{0} - {1}", users2.FirstName, users2.LastName);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Output should be:
All users in Support Department.
John - Johnson
Mike - Mikeson
Get single user with firstname starting with Pau
Paul - Paulson