【发布时间】:2022-09-24 01:35:53
【问题描述】:
我的 DOTNET 6 API 中有一个名为 FileManagerContext 的 DbContext:
public class FileManagerContext : DbContext {
public FileManagerContext(DbContextOptions<FileManagerContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
}
}
这是一个非常简单的DbContext,里面有一个简单的实体。无论如何,我也有这个appsettings.json:
{
\"Logging\": {
\"LogLevel\": {
\"Default\": \"Information\",
\"Microsoft.AspNetCore\": \"Warning\"
}
},
\"ConnectionStrings\": {
\"DefaultConnection\": \"Server=localhost;Database=FM;User=SA;Password=1234;\"
},
\"AllowedHosts\": \"*\"
}
这是Program.cs\'s 顶级语句中的启动sn-p:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<FileManagerContext>(
opt => opt.UseSqlServer(\"name=DefaultConnection\"));
在这种情况下,我可以使用迁移。一切顺利。我可以添加迁移,并且可以成功更新数据库。但是当我运行应用程序并尝试使用 DbContext 时,我收到了这个错误:
System.InvalidOperationException:使用了命名连接字符串, 但在应用程序中找不到名称 \'DefaultConnection\' 配置。请注意,仅支持命名连接字符串 当使用 \'IConfiguration\' 和服务提供者时,例如在 典型的 ASP.NET Core 应用程序。看 https://go.microsoft.com/fwlink/?linkid=850912 了解更多信息。
我也尝试过像这样获取连接字符串:
var cs = builder.Configuration.GetConnectionString(\"DefaultConnection\");但它返回null。有人可以帮我解决吗?
标签: c# .net-core entity-framework-core .net-6.0 ef-core-6.0