Monday, January 16, 2012

Generating a LINQ to SQL DataContext for VS Express for Windows Phone

As you may know, you can generate a Windows Phone DataContext based on an existing database for use with Windows Phone Mango “Local Database”, as described here and here. But this feature is only available if you own a paid Visual Studio edition (Pro or higher), as the Express editions do not support add-ins.

But users of Visual Studio 2010 Express for Windows Phone can now also take advantage of all the productivity benefits of the “Database First” approach to Local Database development on Windows Phone.

Provided you have a SQL Server Compact Database ready, designed according to the guidelines here, and possibly created by using a tool, you can follow this simple procedure to generate and add the DataContext to your Windows Phone solution.

Anyone using the Express tools will notice that SQLMetal (which is used behind the scenes to create the DataContext file) is not included. You can get it from the Microsoft SDK bundle You only need to choose the following options to get the required files.


Then go to the download page for my ExportSqlCe tool, and download the latest version of the Exportsqlce.exe command line utility.

You can now generate a DataContext file from the command line, as documented here.

In this example, I will generate a DataContext based on the Chinook sample database.

exportsqlce wpdc "Data Source=C:\projects\Chinook\Chinook.sdf" C:\temp\Chinook.cs

Notice that the format of the database must be SQL Server Compact 3.5.

In Visual Studio, open your Windows Mango project, and from Solution Explorer, select Add, Existing Item, and browse to the file the was just created.


Remember to add a reference to System.Data.Linq to your project.


You can now start using the generated DataContext in your project!

using (ChinookContext db = new ChinookContext(ChinookContext.ConnectionString))
db.LogDebug = true;

var artist = db.Artists.FirstOrDefault();
artist.Name = Guid.NewGuid().ToString();


Happy coding…


Jimclass_Heroe said...

Hello Erik,

I'm attempted to create a Windows Phone 8 Encyclopedia app deployed with a SQL CE database that's preloaded with data. The app needs to simply read from this database and populate the data on the UI.

Your SQLCE Toolbox has been a huge life safer and I've successfully created a database and the corresponding datacontext file. However, could you write an updated post on how to successfully connect to the database (both read-only and copy) and set the datacontext? Most of the posts for Windows Phone are from last year. Any help would be appreciated, as I've been struggling with this for a couple of weeks now.

Thank you in advance!


ErikEJ said...

Ebsan: see and