【问题标题】:How to share dbcontext to entire razor web application?如何将 dbcontext 共享到整个 Razor Web 应用程序?
【发布时间】:2023-01-22 15:07:01
【问题描述】:

我读了很多线程在 aspnet 中说共享连接数据库到控制器和页面是通过依赖注入。所以我遵循本教程tutorial。但是在实施之后。 dotnet-ef 迁移不起作用。在它的工作之前。当我删除 dbcontext 服务时迁移工作。并将配置放在 applicationcontext 类中。这是什么原因?

无法创建“ApplicationContext”类型的对象。为了 设计时支持的不同模式,请参阅 https://go.microsoft.com/fwlink/?linkid=851728

程序.cs

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ApplicationContext>(options => 
    options.UseMySQL(builder.Configuration.GetConnectionString("DefaultConnection")));

ApplicationContext.cs

public class ApplicationContext : DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) {}
    public DbSet<User> Users { get; set; }
}

【问题讨论】:

  • 请阐明您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: c# asp.net entity-framework razor


【解决方案1】:

默认情况下,ASP.NET Core 应用程序将通过定义的中间件创建和管理 HttpRequest 范围。 您想要和需要的是在一开始就创建数据库上下文,这样它将解析依赖注入的 dbContext。

您可以通过在执行 program.cs 时创建范围来获得此信息并确保创建了数据库 (你可能想用 ovveriding OnModelCreating(ModelBuilder modelBuilder) 播种它)

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<YoureContext>(options =>
{
    options.UseMySQL(builder.Configuration.GetConnectionString("DefaultConnectioning"))
});


var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<YoureContext>();
    //context.Database.EnsureDeleted(); //For deleting and Re-Seedng the Database
    context.Database.EnsureCreated();
}

【讨论】:

    猜你喜欢
    • 2020-05-20
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多