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

标签 c# asp.net asp.net-core asp.net-web-api entity-framework-6

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

最佳答案

这是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。

关于c# - 在 ASP.NET Core 6 Program.cs 中配置 EF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71397260/

相关文章:

c# - 在单独的项目 Asp.net Core MVC 中进行本地化

c# - 泛型协变和显式转换

c# - 如何在尊重路由配置的同时解析 Kentico Cloud 中的内容项链接?

c# - 在 MVC 中,为 session 赋值时,未将对象引用设置为对象异常的实例

c# - 使用颜色代码从 Gridview 导出到 excel

html - 为什么发送邮件时不在另一个div的底部添加一个div?

asp.net-mvc - ASP.NET Core 2.0 : HTTP requests timeout, 但 HTTPS 请求没有

c# - Net Core 集成测试 : Run Startup. cs 和来自其他程序的配置

c# - 在服务注册期间确定 ASP.NET Core MVC Area

c# - 在 pythonnet 中导入 .NET 自定义类时出现 ModuleNotFoundError