You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行add-migration时出现connectionString为空错误,寻求技术帮助

Fixing "Value cannot be null. Parameter name: connectionString" in EF Core Add-Migration

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:

  1. Configuration Section Name Mismatch
    The Configuration.GetConnectionString("LibraryConnection") method in your Startup.cs expects connection strings to be stored under a ConnectionStrings (plural) section in your config file. But you've used ConnectionString (singular) instead—this is why the method returns null, triggering the error.
  2. Non-Generic DbContextOptions (Optional but Recommended)
    Your LibraryContext constructor uses the non-generic DbContextOptions type, 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"
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:22:16