I'm new to asp.net core and the task I want to do should be very simple. Using Visual Studio, I'm trying to link a .mdf file to my project as a local database. As I want to make it work for several computers, I need to find the data directory folder path from appsettings.json. Therefore, after some researches, the best way to do that is using the |DataDirectory| substitution string.
The problem is that my website can't reach my mdf file this way and it generates an ArgumentException : "Invalid value for key 'attachdbfilename'". Although I found some topics about this issue, none of these answered to my question.
I've already tried to use the full path to find my file and it worked but as I said, I need to find it from several computers.
Here are Startup.cs and appsettings.json
Startup.cs :
public class Startup
{
public Startup(IConfiguration configuration)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "App_Data");
AppDomain.CurrentDomain.SetData("DataDirectory", path);
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
[...]
}
My connection string, in appsettings.json :
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDbFilename=|DataDirectory|\\aspnet-MatrixCalculatorApp-db.mdf;Trusted_Connection=True;MultipleActiveResultSets=true"
},
If needed, I can also provide the stack trace.
Thank you in advance for your help.