Set AttachDbFilename as Relative Path in .NET Core

Raymond Raymond visibility 5,959 event 2018-07-08 access_time 4 years ago language English

.NET Framework, you can use |DataDirectory| to configure connection string when connecting to SQL Server database file via attach mode:

AttachDbFilename=|DataDirectory|\dbname.mdf

In .NET Core, you cannot directly set SQL Server Express connection string by using any tokens directly. There is a workaround that can be used to get it work.

Connection string configuration in appSetting.json

"ConnectionStrings": {
     "KontextCoreConnection": "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=%CONTENTROOTPATH%\\App_Data\\kontext-docu.mdf;Integrated Security=True;Connect Timeout=30",
     "KontextDocuConnection": "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=%CONTENTROOTPATH%\\App_Data\\kontext-docu.mdf;Integrated Security=True;Connect Timeout=30"
   }

The above code snippet configures two connection strings with a token %CONTENTROOTPATH%.

Parse the tokens when reading connection strings

Based on the token used in the configurations, replace it with the actual content root path.

// Replace connection string tokens
             var connStrCore = Configuration.GetConnectionString(Constants.KontextCoreConnectionName);
             var connStrDocu = Configuration.GetConnectionString(Constants.KontextDocuConnectionName);
             if (connStrCore.Contains(Constants.ContentRootPathToken))
                 connStrCore = connStrCore.Replace(Constants.ContentRootPathToken, Env.ContentRootPath);
             if (connStrDocu.Contains(Constants.ContentRootPathToken))
                 connStrDocu = connStrDocu.Replace(Constants.ContentRootPathToken, Env.ContentRootPath);

            // Add database context
             services.AddDbContext<ApplicationDbContext>(options =>
             {
                 if (dbConfig.CoreDbType == DatabaseType.SQLite)
                 {
                     options.UseSqlite(connStrCore,
                         b => b.MigrationsAssembly("Kontext.Docu.Web.Portals"));
                 }
                 else
                 {
                     options.UseSqlServer(connStrDocu,
                         b => b.MigrationsAssembly("Kontext.Docu.Web.Portals"));
                 }
                 // Register context data models.
                 options.UseContextProjectShared();
             });

In Constants class, a static field is defined to indicate the replacement token.

public readonly static string ContentRootPathToken = "%CONTENTROOTPATH%";

Of course, you can change the value to any token you like as long as it is consistent with your configuration file.

More from Kontext
info Last modified by Raymond 4 years ago copyright This page is subject to Site terms.
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts