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

发布于 2025-01-12 11:30:03 字数 1251 浏览 0 评论 0原文

我被要求制作一个 ASP.NET Core 6 webAPI,我之前没有使用 Microsoft 东西的经验,我正在关注 MS Docs 此处 在文档中,他们教授如何配置Startup.cs 文件中的 EF 具有 Main 方法(他们忘记更新文档?),该方法在 >ASP.NET Core 6,我的 Program.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();

如何将 EF 添加到 在这种情况下是 Program.cs 吗?

编辑:以及如何添加CreateDbIfNotExist() (Docs) 方法,但没有类可以驻留在其中?

I'm asked to make an ASP.NET Core 6 webAPI, I have no prior experience with Microsoft stuff, I'm following MS Docs Here In the Docs they teach how to configure EF in a Startup.cs file with a Main method(they forgot to update the docs ?), which is not there in an ASP.NET Core 6, My Program.cs Doesn't have a Main method and looks like this:

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();

How to add the EF to Program.cs in this case ?

EDIT: and how to add the CreateDbIfNotExist() (Docs) method while there is no class for it to reside in ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薄情伤 2025-01-19 11:30:03

这是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)));

用您的数据更改YOUR_DBCONTEXT和CONNECTION_STRING。

this is the code in 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)));

change YOUR_DBCONTEXT and CONNECTION_STRING with your data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文