Click here to Skip to main content
13,255,340 members (49,439 online)
Click here to Skip to main content
Add your own
alternative version


11 bookmarked
Posted 22 May 2013

SQL Server Compact (CE) Database Maintenance Helper

, 22 May 2013
Rate this:
Please Sign up or sign in to vote.
A small .NET class library for maintaining SQL CE database schema written in C#.


SQL server CE database might be a good option for smaller projects which require an embedded database and simple deployment process. Since the SQL CE (version 4) database does not support batch queries it might be difficult or boring work to organize updates propagation with new versions of the application. This article presents a .net class library that encapsulates the SQL CE database maintenance/updates functionality by delivering and executing SQL update commands in a structured way. Commands (SQL DML/DDL) are wrapped in a XML “Update” object. 

The idea of this project originated from a desktop application project which has been deployed to few locations and later it needed new version and the ability to upgrade the db schema on its own. I believe desktop developers have come across the same scenario many times. In fact, I wouldn't see anything wrong in using it in a web projects when using SQL Compact.


In a nutshell, here is how it is working in an application lifecycle:

  • During the development database schema modifications (in form of SQL DDL/DML) are added to the XML file which is part of the project (embedded resource) and has simple and well defined structure (presented later). Because we are dealing with SQL CE database every command is separated in in its own tag, like this:
<Command>ALTER TABLE [Employee] ADD COLUMN [Department_Fk] BIGINT null;</Command>
  • The library’s UpdateManager .ProcessUpdates method has to be called as a very first action on a database before application normal functionality starts so that it can check/bring up the database to the newest version.
  • XML file gets desterilized and commands are executed one by one with ADO .net.
  • Database updates log (version info) is persisted into library’s dedicated table that gets created when the library is used for the first time.
  • Client application works as normal until its new version arrives which again detects schema updates via UpdateManager .

The update commands are grouped in an object called Update which is represented by SqlCEHelper.Updates.Update class:

public class Update
    public int Number { get; set; }

    public List<String> Commands { get; set; }

    public string Comments { get; set; }

Commands are executed one by one in a loop.

foreach (var command in update.Commands)
    c.CommandText = command;
    catch (Exception exception)
        var sqlCeHelperUpdateException
            = new SqlCEHelperUpdateException
                ("An error occurred while performing database updates.",
                {ErroredCommand = command};
        sqlCeHelperUpdateException.Data.Add(0, update);

        throw sqlCeHelperUpdateException;

An update is considered as successful only if all commands run without exceptions. When the entire update has successfully run a record is added the library’s dedicated table with the update number which means that the database is in higher version. Any exception thrown during executing update commands will stop the update procedure and will throw the SqlCEHelperUpdateException.

Using the code

The library code is not complicated at all and very simple to use. The demo project is wrapped into simple Winforms app and its main form Load event. There is nothing stopping developers to put it anywhere in their architectures as long as the code runs before first request to the database.

To begin using the code, reference the SqlCEHelper.Updates binaries or the project source. Create an instance of the SqlCEHelper.Updates.UpdateManager. Next call Configure method which requires simple Configuration object with the connection string and a string DbUpdatesLogTableName property. In the demo code I use "ExampleSqlHelperWinFormsApplication" value for that property. It is a table name for maintaining updates information. Once chosen the property value must remain unchanged for the life of the application.

// Intialize a new update manager
var updateManager = new UpdateManager();

// Build up the configuration
var configuration = new SqlCEHelper.Updates.Configuration ()
        ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString,
        // This must app app life scope variable:
        DbUpdatesLogTableName = "ExampleSqlHelperWinFormsApplication"

// Configure the updater

Optionally, client application can subscribe to some events to inform the user that the db is being updated after they launched new version. Since this is just a Winforms app I append messages to a text box like here:

// Show some progress of updates,
// by listeninig to the updater events
updateManager.PerformingUpdate += (s, a) =>
            ("Applying database update: {0}",
updateManager.PerformedUpdate += (s, a) =>
    textBox1.AppendText(" - success.");
updateManager.DbIsUptoDate += (s, a) =>
        textBox1.AppendText("The database is up to date!");

Finally call the ProcessUpdates method which requires a XML string with updates. It is recommended to create a solution-included XML file that maintains history of all changes for lifetime of the application. In the demo project I called it DbUpdates.xml and it is set as embedded resource.

<?xml version="1.0" encoding="utf-16"?>
<DatabaseUpdates xmlns:xsi="" xmlns:xsd="">

      Update Number must be uniqe across application lifetime.
        Entire history of updates should remin here,
        so any old version db would get updated accordingly.

        <Command>ALTER TABLE [Employee] ADD COLUMN [DateBorn] DATETIME null;</Command>
      <Comments>Added date born</Comments>


        <Command>ALTER TABLE [Employee] ADD COLUMN [Department_Fk] BIGINT null;</Command>

          create table [Department] (
          NAME NVARCHAR(500) NOT NULL,
          primary key (Id) );

          alter table [Employee]
          add constraint Employee_Department_Fk
          foreign key (Department_Fk)
          references [Department](Id);</Command>

      <Comments>Implemented Departments and added foregin key constraint</Comments>


Such file would usually reside somewhere within data access layer or a client application like in the demo. So here is the how to read the embedded resource XML and start the updates procedure:

// Read the updates XML
// (The Updates XML build action must be set as Embedded Resource)
string updatesXml = (new StreamReader(Assembly.GetExecutingAssembly()

    // Perform updates here
catch (Exception ex)
    MessageBox.Show(ex.Message, "Error");

Now the application can continue its execution as normal with the database being now up to date.

The app run for the first time:

The app run for the second time:

Points of Interest

With some changes and refactoring this code could potentially be made more generic and used for other databases. In fact nothing would stop one to get it quickly working against standard SQL server where batch queries are supported. Currently though the librabry is called SQLCEHelper so at least the name would need refactoring.

The code has proven to work updating CE database with several thousands of records in few deployment environments. It obviously works well even though my client application is using nNibernate for its DAL. I realize that it is still far from perfect (events in particular could be improved a lot) but it might be used as starting foundations for further development or used as is.


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


About the Author

Tadeusz Kaliszewski
United Kingdom United Kingdom
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 4 Pin
fredatcodeproject23-May-13 2:27
memberfredatcodeproject23-May-13 2:27 

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.171114.1 | Last Updated 22 May 2013
Article Copyright 2013 by Tadeusz Kaliszewski
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid