Recently I have been trying to run some user acceptance tests and have been struggling to generate a membership database for use with the asp.net membership provider on the fly and then clean up afterwards. I like to generate test database with unique names as not to clash with other tests that might be running on the test box and this had been proving rather hard.
I started of trying to generate some scripts from an existing database but I also needed to populate the tables with some standing data and it was all starting to look very ugly so I started to look at how I could run the aspnet_regsql.exe from code and opened it up in dotPeek. In doing so I came across some calls to a static class in the System.Web assembly called SqlServices in the System.Web.Management namespace. aspnet_regsql.exe uses this class to generate the build scripts for creating the application database based on the parameters provided but the class also provides methods that allow you to generate a database there and then. The methods you should be interested in are:
public static void Install(string server, string user, string password, string database, SqlFeatures features)
public static void Install(string server, string database, SqlFeatures features)
public static void Install(string database, SqlFeatures features, string connectionString)
The SqlFeatures are flags which can be applied in combination, the features available are Membership, Profile, RoleManager and Personalization. There are two overloads, None and All. In the end I went with the server name and database name overload.
var membershipDatabaseName = "<TestProject>Membership" + Guid.NewGuid().ToString("N");
SqlServices.Install("localhost", membershipDatabaseName, SqlFeatures.All);
Just remember to clean up when your done!