1

Is it possible to force EF 6 to create a sql server database in a specific folder rather than the standard folder in a code first scenario? I have done quite a few searches but could not find any useful information. Thanks.

PS:

connection string:

<add name="BlaDbContext" connectionString="Data Source=127.0.0.1,1234;Initial Catalog=xxx;User Id=xxx;Password=xxx;" providerName="System.Data.SqlClient" />

Also tried to include DataDirectory and manipulate it from my console app as suggested by Steve Greene.

PPS:

Also tried:

context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
    @"  ALTER DATABASE [DB] MODIFY FILE 
        (
           Name = DB,
           Filename = 'D:\Databases\DB.mdf'
        );

        ALTER DATABASE [DB] MODIFY FILE 
        (
           Name = DB_log, 
           Filename = 'D:\Databases\DB_log.ldf'
        );
    ");
cs0815
  • 16,751
  • 45
  • 136
  • 299

1 Answers1

-1

You can override the data folder:

// Set |DataDirectory| value
AppDomain.CurrentDomain.SetData("DataDirectory", "C:\MyFolder");

https://msdn.microsoft.com/en-us/library/37z40s1c(v=vs.110).aspx

Steve Greene
  • 12,029
  • 1
  • 33
  • 54
  • Right, that is for localdb. If you are using SQL Server the easiest thing to do is go create the database where you want outside of EF and refer to it in your connection string. If that is not doable you would probably need to write a custom initializer http://blogs.microsoft.co.il/gilf/2011/05/30/creating-a-code-first-database-initializer-strategy/ and include the SQL code to create the database where you want: context.Database.ExecuteSqlCommand("CREATE DATABASE xxx ON PRIMARY ( NAME = N'xxx', FILENAME = N'C:\MyPath\xxx.mdf') ... – Steve Greene May 29 '15 at 16:41
  • Thanks I have written a custom initializer already. See PPS in my question, which shows a fraction. However, I do not think I can manipulate the CREATE DATABASE command of EF ... would love to though, if you know how. – cs0815 May 30 '15 at 09:08
  • 1
    Similar question here with a partial answer that you might be able to tweak http://stackoverflow.com/questions/30451738/ef-code-first-how-to-initialize-database-on-a-specific-location-hdd – Steve Greene May 30 '15 at 16:18
  • Thanks Steve looks promising. – cs0815 May 31 '15 at 11:47