does anybody know how to spedify exact .mdf/.log file location during EF CodeFirst database initialization?
For a debug and testing scenario (but specifying exact DB files location can be useful in production as well), I'd like to re-deploy database during application start-up, but also I'd like to create DB files on a specific location (e.g. secong hard drive).
public class MyCustomInitialized : DropCreateDatabaseAlways<MyContext>
{
public override void InitializeDatabase(MyContext context)
{
if (context.Database.Exists())
{
// set the database to SINGLE_USER so it can be dropped
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "ALTER DATABASE [" + context.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
// drop the database
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "USE master DROP DATABASE [" + context.Database.Connection.Database + "]");
// Doesn't work yet
var directoryPath = ConfigurationManager.AppSettings["DatabaseDirectoryPath"];
var fileName = ConfigurationManager.AppSettings["DatabaseFileName"];
if(!Database.Exists()) {
var qry = string.Format(
"USE master CREATE DATABASE {0}" + Environment.NewLine +
"ON PRIMARY" + Environment.NewLine +
"( NAME = {0}, FILENAME = '{1}')" + Environment.NewLine +
"LOG ON" + Environment.NewLine +
"( NAME = {2}, FILENAME = '{3}')" + Environment.NewLine
, this.Database.Connection.Database,
Path.Combine(directoryPath, fileName + ".mdf"),
this.Database.Connection.Database + "_log",
Path.Combine(directoryPath, fileName + "_log.ldf"));
// -- EXCEPTION HERE,
Database.ExecuteSqlCommand(qry);
Database.ExecuteSqlCommand("USE " + this.Database.Connection.Database);
}
base.InitializeDatabase(context);
}
}
The exeption I get:
Cannot open database "DatabaseName" requested by the login. The login failed. Login failed for user 'SomeUser'. A severe error occurred on the current command. The results, if any, should be discarded.
If the database can be created by EF during initialization, how this initialization can be overriden?
Thanks, Tom