使用VS2017等工具时,add-migration无法读取appsettings.json连接字符串
add-migration in ASP.NET Core 2 I see exactly what's going on here—your custom UseContentRoot setup is throwing off EF Core's migration tools when they try to locate appsettings.json. Let's break down the problem and walk through solutions.
Why This Happens
When you run add-migration, the EF Core tools are the main running process, not your application. Your current code sets the content root to the directory of the process executable, which for the EF tools isn't your project folder where appsettings.json lives. That's why the connection string can't be found.
Solution 1: Conditionally Set the Content Root
Modify your BuildWebHost method to only apply the custom content root when your app is running normally, not when EF tools are using it. We can detect this by checking if our assembly is the entry point:
using System.Reflection; using System.Diagnostics; public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) // Only override content root if we're running the actual application .UseContentRoot(Assembly.GetEntryAssembly() == Assembly.GetExecutingAssembly() ? Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) : Directory.GetCurrentDirectory()) .UseStartup<Startup>() .UseNLog() .Build();
This way, EF tools will use the default content root (your project directory) where appsettings.json resides.
Solution 2: Manually Load Configuration in Your DbContext
If you prefer a more direct approach, explicitly load the configuration file in your DbContext's OnConfiguring method to ensure it always looks in the project directory:
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System.IO; public class YourDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); optionsBuilder.UseSqlServer(config.GetConnectionString("YourConnectionStringKey")); } } }
Just make sure you run the add-migration command from your project's root directory (where appsettings.json is stored).
Solution 3: Pass the Connection String Directly via Command Line
For a quick fix without modifying code, you can pass the connection string directly when running the migration command:
dotnet ef migrations add YourMigrationName --connection "Server=yourserver;Database=yourdb;Trusted_Connection=True;"
This skips reading from appsettings.json entirely for the migration command.
After trying any of these solutions, run add-migration again—it should now successfully access the connection string.
内容的提问来源于stack exchange,提问作者dergroncki

