views:

1808

answers:

1

I'd like to use Visual Studio 2008 IDE for editing my local database schema for a SQL Server Compact 3.5 database. However, everything in the documentation and in the UI seems to make an assumption that the application/assembly only wants to use a single database and never wishes to create new ones based on the existing schema.

I'd like to be able to edit the DB schema using visual tools and then to have a mechanism for creating new database files based on the edited schema. This way each document that my application creates would be stored in their own separate database files (.sdf). Furthermore, for the purpose of unit testing, I'd like to be able to create empty temporary .sdf files in order to run my unit tests on an empty database.

The only way I know how to create new empty databases using an existing schema is just to copy my master .sdf file to a new file.

What would be the recommended way to create new .sdf files using C# code? I.e., how to implement MyModel.Create("foo.sdf") so that it creates .sdf files using the schema I've created in Visual Studio.

EDIT: After a long investigation, I ended up ditching VS2008 local database .sdf editor completely and started creating new .sdf files by using LINQ-to-SQL. I now just specify a bunch of C# classes, annotate them to work with LINQ-to-SQL and create new database files by calling my DataContext's CreateDatabase method. MSDN has a good document on it: How to: Dynamically Create a Database (LINQ to SQL)

+3  A: 

Create a "model.sdf" database, that contains the schema, and possibly needed initial data. If you want to create a new database, you create a copy from this model.

You could also create the Sql-DDL from an existing database (alternative link), then create an empty database and execute this SQL on it. This will be a lot slower.

GvS
So in C# code, I just use file operations to copy "model.sdf" to "foo.sdf" when I want a new instance? There's no API for "read schema from <model.sdf>, then create a new .sdf file"?
Nurpax
I've edited my answer to include a solution for this also. Still think the copy will be the easiest and fastest.
GvS
Thanks for the answer!Is there an idiomatic way to include the .sdf file in the .net assembly? Dependees of my data model dll should ideally not need to know about this .sdf file at all.
Nurpax
Responding to my above comment: I guess an easy way is to link it into the dll as a resource. This way the model is conveniently stored inside the dll and doesn't require separate installation.
Nurpax
For installation, it's easier, but it will make it more difficult to update only the database later.
GvS