Allowing SQL Server Compact databases to work in ASP.NET applications

Posted: (EET/GMT+2)

 

Web applications are what most developers seem interested in, and this interest also raises the need to write single-person ASP.NET web applications. For instance, you might run your site on a service provider that doesn't include a full-blown SQL Server installation. But with SQL Server Compact, you can simply copy your database .SDF file to the server, some additional DLLs, and you are set.

Except that if you try this, your ASP.NET application will fail with the following error message:

System.NotSupportedException was unhandled
by user code
Message="SQL Server Compact is not intended for ASP.NET development."
Source="System.Data.SqlServerCe"

Darn! What now? Luckily, there's a solution: add some code to your application's Application_Start event handler in Global.asax.cs, and you can work with SQL Server Compact databases even in your web applications.

void Application_Start(object sender, EventArgs e)
{
  AppDomain.CurrentDomain.SetData(
    "SQLServerCompactEditionUnderWebHosting", true);
}

With this code, you won't see the error again. Of course, you should remember that SQL Server Compact was not designed for multi-user web applications, and thus the error message is valid. But, if you are sure only a single user (you) will access the database at one time, then it's OK to work around the error.