我一直在尝试创建迁移,然后更新数据库(使用 EF Core 工具和 SSMS 检查数据库)。我一直在挣扎,因为我有不同的项目。我的解决方案的组织如下:
我想在
VSC.Repo
中进行迁移和相关的数据库交互。这意味着上下文在这个项目中。除此之外,我的连接字符串位于默认的应用程序设置中,位于 VSC.API
(不同的程序集)中。我尝试了各种方法来尝试从那里获取连接字符串,但是当我在 VSC.Repo
项目中运行“dotnet ef 数据库更新”时,我总是收到以下错误:
这是我的上下文类:
public class DataContext : DbContext
{
private readonly string connectionString;
public DataContext()
{
}
public DataContext(DbContextOptions<DataContext> options, IConfiguration configuration) : base(options)
{
connectionString = configuration.GetSection("ConnectionStrings:DefaultConnection").Value;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(connectionString);
}
我不知道我做错了什么。任何帮助我将不胜感激。
编辑:使用硬编码字符串,它工作得很好,但这是不好的做法,我不想以这种方式实现。
appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "server=localhost;database=vscDatabase;trusted_connection=true;TrustServerCertificate=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
程序.cs:
WebApplicationBuilder? builder =
WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
var connectionString =
builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DataContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//builder.AddRepoConfigurations();
var app = builder.Build();
好吧,@Panagiotis Kanavos 发现我在错误的项目中执行命令,更准确地说,是在没有 program.cs 的项目中执行命令,这就是问题所在。当我执行正确的操作时,效果很好。
我认为你必须设置文件json选择属性=>复制到输出目录=>选择copyIfNew或始终复制