DLinq and detecting database schema changes
Posted
Tuesday, May 30, 2006 10:54 AM
by
Maurice
Previously I stated that I dislike the separation between the code and the database schema. A first look at SqlMetal.exe, a utility that comes with DLinq suggested that it might ease the problems and guess what, it does :-)
I created a small sample app and added the following command to the pre-build event:
"c:\Program Files\LINQ Preview\Bin\SqlMetal.exe" /database:Northwind /code:"$(ProjectDir)Northwind.vb" /language:vb
Build the project to have the Northwind.vb file generated and include it in the project.
Next I added the following code:
Sub main()
Dim northwind AsNew Northwind(My.Settings.DataConnection)
' Build a list cities with multiple customers
Dim results = From customer In ( _
From customer In northwind.Customers _
GroupBy customer.Country, customer.City _
Select it.Key, it, Count(it)) _
Where customer.Count > 1 _
Select customer _
OrderBy customer.Count Descending, customer.Key.Country, customer.Key.City
ForEach row In results
' Print the country and city
Console.WriteLine("Country: {0} - City: {1} - Count: {2}", _
row.Key.Country, row.Key.City, row.Count)
' Print the customers for the city
ForEach customer In row.it
Console.WriteLine(" => {0}", customer.CompanyName)
Next
Next
Console.ReadKey()
EndSub
Now build and run the project and you will see the output appear.
Now go open the table schema for the Customers table and change the City column name to TheCity. Save the changes and try to run. This time you will get compile errors on every reference to the City property because its no longer valid.
Easy to do and so much better than runtime errors that the City column name is invalid.
Enjoy!