Self configuring embedded database in C#

I recently needed to write a C# desktop application which used its own small database. I wanted something that could be easily deployed with xcopy, so I didn’t want to connect to any external database engine. So I used SQL Compact Edition v4. Since I’ve recently been having success with PetaPoco as a micro-ORM type thing, I thought that I’d try that too. I had the idea that the database could configure itself when the program starts, so that’s what I set out to try. I was surprised how easy it was. This is what I did to make a proof-of-concept:

  • Create an empty Console Application in Visual Studio 2012
  • Use NuGet to add references to PetaPoco.Core (v5.0.1) and Microsoft.SqlServer.Compact (v 4.0.8876.1)
  • Have this code as the C# program

That’s all there is to it, easy. If you corrupt the database, then the code will re-create a clean database file next time it runs. You don’t need to include an sdf file in your project, because the database will be created by the code. Obviously this is an extremely trivial example, but it seems to work great.