[英]How to share dbcontext to entire razor web application?
我讀了很多線程在 as.net 中說要將連接數據庫共享到 controller 並且頁面是通過依賴注入。 所以我遵循本教程教程。 但是在實施之后。 do.net-ef 遷移不起作用。 在它的工作之前。 當我刪除 dbcontext 服務時遷移工作。 並將配置放在 applicationcontext class 中。這是什么原因造成的?
無法創建“ApplicationContext”類型的 object。 有關設計時支持的不同模式,請參閱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; }
}
ASP.NET 核心應用會通過定義的中間件默認創建和管理一個HttpRequest scope。 您想要和需要的是在一開始就創建數據庫上下文,這樣它將解析依賴注入的 dbContext。
您可以通過在執行 program.cs 時創建一個 scope 來獲得它,並確保創建了數據庫(您可能希望使用 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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.