运行add-migration时出现connectionString为空错误,寻求技术帮助
Hey there, let's break down and fix this connection string issue you're hitting when running add-migration "Initial Migration".
Root Cause
The main problem here is a small but critical typo in your appsettings.json file, plus a minor best practice tweak for your LibraryContext:
- Configuration Section Name Mismatch
TheConfiguration.GetConnectionString("LibraryConnection")method in yourStartup.csexpects connection strings to be stored under aConnectionStrings(plural) section in your config file. But you've usedConnectionString(singular) instead—this is why the method returnsnull, triggering the error. - Non-Generic DbContextOptions (Optional but Recommended)
YourLibraryContextconstructor uses the non-genericDbContextOptionstype, which can lead to ambiguity in dependency injection. Using the generic version is the standard EF Core practice.
Step-by-Step Fixes
1. Correct the appsettings.json Section Name
Update your appsettings.json to use the plural ConnectionStrings key:
{ "ConnectionStrings": { "LibraryConnection": "Server(localdb)\\MSSQLLocalDB;Database=Library_Dev;Trusted_Connection=True;MultipleActiveResultSets=true" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } } }
2. Update LibraryContext Constructor (Recommended)
Modify your LibraryContext to use the generic DbContextOptions<LibraryContext>:
public class LibraryContext : DbContext { public LibraryContext(DbContextOptions<LibraryContext> options) : base(options) { } public DbSet<Patron> Patrons { get; set; } }
3. Verify Startup Project
Ensure the project containing your appsettings.json (your web project) is set as the startup project in your solution. EF Core uses the startup project's configuration when running migrations:
- In Visual Studio: Right-click your web project in Solution Explorer → Set as Startup Project
- If using Package Manager Console: Run
Set-StartupProject YourWebProjectName
After making these changes, re-run add-migration "Initial Migration"—it should pick up the connection string correctly now.
内容的提问来源于stack exchange,提问作者CodeMonkey

