C# Dotnet WebAPI EFcore 中 CS1030 警告解决

在使用以下命令创建类后,会出现CS1030的错误 Scaffold-DbContext “Server=localhost;Database=xx;User ID=postgres;Password=wantgirl;” Npgsql.EntityFrameworkCore.PostgreSQL -

在使用以下命令创建类后,会出现CS1030的错误

Scaffold-DbContext “Server=localhost;Database=xx;User ID=postgres;Password=wantgirl;” Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models

解决方式:

将报错内容修改为以下内容,将数据库连接从该文件转向appsettings.json文件

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();

        var connectionString = configuration.GetConnectionString("PostgreSql");
        optionsBuilder.UseNpgsql(connectionString);
    }
}

修改对应的appsettings.json文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "PostgreSql": "User ID=xxxxx;Password=xxxxxxx;Host=xxxxx;Port=5432;Database=xxxx"
  },
  "AllowedHosts": "*"
}

修改 Program.cs 添加对 DbContext 的依赖注入配置:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<_3dPinterMonitorContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("PostgreSql")));
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();

说明:如果出现Build failed.的报错,检查一下项目中是不是有报错未解决,解决报错后再次运行即可

LICENSED UNDER CC BY-NC-SA 4.0
Comment