Attach local database using .NET Core and CMS 12
In my CMS 11 solution I used the variable |DataDirectory| to point out the App_Data folder where my database file is placed and that workd just fine. Is Net Core I tried to use the same:
"ConnectionStrings": {
"EPiServerDB": "Data Source=(LocalDb)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\EPiServerDB_f6c7a112.mdf;Initial Catalog=EPiServerDB_f6c7a112;Connection Timeout=60;Integrated Security=True;MultipleActiveResultSets=True"
}
In CMS 12 using Net Core, the |DataDictionary| does not work anymore and need to be replaced in some way. I found this that I thought was my solution:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
string baseDir = env.ContentRootPath;
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(baseDir, "App_Data"));
}
What happend was that when calling ConfigureCmsDefaults() which is done in Program.cs, Episerver tries to connect to the database but the connectionstring is not modified so that fails. A strange behavior was that the code then never reached the Configure(...) method and I could never understand why until I set the real physical path to the database in the connectionstring.
"ConnectionStrings": {
"EPiServerDB": "Data Source=(LocalDb)\\MSSQLLocalDB;AttachDbFilename=D:\\Projekt\\Web\\App_Data\\EPiServerDB_f6c7a112.mdf;Initial Catalog=EPiServerDB_f6c7a112;Connection Timeout=60;Integrated Security=True;MultipleActiveResultSets=True"
}
Then everything worked just fine, but is doesn't look to good and finally I found a solution using PostConfigure.
Connectionstring looks like this:
"ConnectionStrings": {
"EPiServerDB": "Data Source=(LocalDb)\\MSSQLLocalDB;AttachDbFilename=App_Data\\EPiServerDB_f6c7a112.mdf;Initial Catalog=EPiServerDB_f6c7a112;Connection Timeout=60;Integrated Security=True;MultipleActiveResultSets=True",
}
And ConfigureServices like this:
public void ConfigureServices(IServiceCollection services)
{
services.PostConfigure<DataAccessOptions>(o =>
{
o.SetConnectionString(_configuration.GetConnectionString("EPiServerDB").Replace("App_Data", Path.GetFullPath("App_Data")));
});
services.PostConfigure<ApplicationOptions>(o =>
{
o.ConnectionStringOptions.ConnectionString = _configuration.GetConnectionString("EPiServerDB").Replace("App_Data", Path.GetFullPath("App_Data"));
});
}
In this way the connectionstring is modified before Episerver is initiated and the database will be attached correctly.
Comments