【问题标题】:Why I get Value cannot be null. (Parameter 'connectionString') error message after Adding Migrations为什么我得到 Value 不能为空。添加迁移后的(参数'connectionString')错误消息
【发布时间】:2022-01-05 21:05:06
【问题描述】:

我在尝试Add-Migration 时收到错误消息并收到错误消息

值不能为空。 (参数'connectionString')

到目前为止,我检查了 Startup.cs 文件并写了一些内容

using Microsoft.EntityFrameworkCore;
using ToDoS.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<TodoContext>(opt =>
   opt.UseSqlServer(connectionString));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

所以我添加了这部分

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<TodoContext>(opt =>
   opt.UseSqlServer(connectionString));

这是我的连接字符串

{
  "Logging": {
    "ConnectionStrings": {
      "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ToDoApp;Integrated Security=True"
    },
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

还有 TodoContext

using Microsoft.EntityFrameworkCore;

namespace ToDoS.Models
{
    public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options) : base(options) { }
        public DbSet<Todo> Todos { get; set; }

    }
}

添加迁移 InitCreate 后,我收到错误消息。我在哪里犯错了?我在这里缺少什么?

【问题讨论】:

    标签: c# asp.net-web-api asp.net-core-mvc


    【解决方案1】:

    连接字符串在 appsettings.json 的 Logging 元素中定义。它应该在根元素中定义:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ToDoApp;Integrated Security=True"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    

    或者,您应该能够使用GetValue 获取字符串:

    var connectionString = builder.Configuration.GetValue<string>("Logging:ConnectionStrings:DefaultConnection");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      相关资源
      最近更新 更多