在 ASP.NET Core 6 Program.cs 中配置 EF

Zek*_*eko 3 c# asp.net asp.net-web-api entity-framework-6 asp.net-core

我被要求制作一个ASP.NET Core 6 webAPI,我对微软的东西没有任何经验,我在这里关注MS文档在文档中他们教如何使用方法EFStartup.cs文件中配置Main(他们忘记更新文档?),这是不存在于 an 中ASP.NET Core 6, MyProgram.cs没有Main方法,看起来像这样:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

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();
Run Code Online (Sandbox Code Playgroud)

Program.cs这种情况下如何添加EF呢?

编辑:以及如何在没有类驻留的情况下添加CreateDbIfNotExist()文档)方法?

小智 5

这是asp.net core 6中的代码:


// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<"YOUR_DBCONTEXT">(option =>
    option.UseSqlServer(builder.Configuration.GetConnectionString(CONNECTION_STRING)));

Run Code Online (Sandbox Code Playgroud)

使用您的数据更改 YOUR_DBCONTEXT 和 CONNECTION_STRING。