英文:
C# and Entity Framework Core v7.0.2 code-first - DbContext database provider error during migration Initialization
问题
我想使用Entity Framework Core 7.0.2和Code First策略初始化我的数据库。
但是当我运行以下命令时:
dotnet ef migrations add InitialCreate --project PreventionCyber.DAL --startup-project PreventionCyber.Web
我遇到了以下错误:
System.InvalidOperationException: 为此DbContext未配置数据库提供程序。可以通过覆盖“DbContext.OnConfiguring”方法或在应用程序服务提供程序上使用“AddDbContext”来配置提供程序。如果使用“AddDbContext”,还请确保您的DbContext类型在其构造函数中接受DbContextOptions<TContext>对象,并将其传递给DbContext的基构造函数。
PCDbContext.cs
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore;
using PreventionCyber.DAL.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PreventionCyber.DAL.Context
{
public class PCDbContext : DbContext
{
public PCDbContext()
{
}
public PCDbContext(DbContextOptions<PCDbContext> options): base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
// Renommage clé primaire
entity.GetProperty("Id")
?.SetColumnName($"{entity.ClrType.Name}Id");
}
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
OnBeforeSaving();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
private void OnBeforeSaving()
{
var entries = ChangeTracker.Entries();
foreach (var entry in entries)
{
if (entry.Entity is BaseEntity trackable)
{
var now = DateTime.UtcNow;
var user = GetCurrentUser();
switch (entry.State)
{
case EntityState.Modified:
trackable.ModifieLe = now;
trackable.ModifiePar = user;
break;
case EntityState.Added:
trackable.CreeLe = now;
trackable.CreePar = user;
trackable.ModifieLe = now;
trackable.ModifiePar = user;
break;
}
}
}
}
private string GetCurrentUser()
{
return "UserName"; // TODO implement your own logic
// If you are using ASP.NET Core, you should look at this answer on StackOverflow
// https://stackoverflow.com/a/48554738/2996339
}
}
}
Program.cs
using Microsoft.EntityFrameworkCore;
using PreventionCyber.DAL.Context;
var builder = WebApplication.CreateBuilder(args);
// 将服务添加到容器中
builder.Services.AddControllersWithViews();
var app = builder.Build();
builder.Services.AddDbContext<DbContext, PCDbContext>(options
=> options.UseSqlServer(builder.Configuration.GetValue<string>("ConnectionStrings:PreventionCyber")));
// 配置HTTP请求管道
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// 默认的HSTS值是30天。您可能需要根据生产场景进行更改,参见 https://aka.ms/aspnetcore-hsts。
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
我不理解这个错误,因为我已经使用DbContextOptions<PCDbContext>
定义了构造函数,并且我还在Program.cs
中将DbContext
添加到builder.Services
中。
有人能找到错误吗?谢谢!
英文:
I want to initialize my database with Entity Framework Core 7.0.2 using a code-first strategy.
But when I launch this command:
dotnet ef migrations add InitialCreate --project PreventionCyber.DAL --startup-project PreventionCyber.Web
I get this error :
> System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
PCDbContext.cs
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore;
using PreventionCyber.DAL.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PreventionCyber.DAL.Context
{
public class PCDbContext : DbContext
{
public PCDbContext()
{
}
public PCDbContext(DbContextOptions<PCDbContext> options): base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
// Renommage clé primaire
entity.GetProperty("Id")
?.SetColumnName($"{entity.ClrType.Name}Id");
}
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
OnBeforeSaving();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
private void OnBeforeSaving()
{
var entries = ChangeTracker.Entries();
foreach (var entry in entries)
{
if (entry.Entity is BaseEntity trackable)
{
var now = DateTime.UtcNow;
var user = GetCurrentUser();
switch (entry.State)
{
case EntityState.Modified:
trackable.ModifieLe = now;
trackable.ModifiePar = user;
break;
case EntityState.Added:
trackable.CreeLe = now;
trackable.CreePar = user;
trackable.ModifieLe = now;
trackable.ModifiePar = user;
break;
}
}
}
}
private string GetCurrentUser()
{
return "UserName"; // TODO implement your own logic
// If you are using ASP.NET Core, you should look at this answer on StackOverflow
// https://stackoverflow.com/a/48554738/2996339
}
}
}
Program.cs
using Microsoft.EntityFrameworkCore;
using PreventionCyber.DAL.Context;
var builder = WebApplication.CreateBuilder(args);
// AddAsync services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
builder.Services.AddDbContext<DbContext, PCDbContext>(options
=> options.UseSqlServer(builder.Configuration.GetValue<string>("ConnectionStrings:PreventionCyber")));
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
I don't understand the error because I've already defined a constructor using DbContextOptions<TContext>
and I added the DbContext
to the builder.Services
too in Program.cs
.
Can anyone find the error? Thanks!
答案1
得分: 0
The error suggested you may need to add the OnConfiguring override method to the PCDbContext class.
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(<yourConnectionString>);
}
英文:
The error suggested you may need to add the OnConfiguring override method to the PCDbContext class.
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(<yourConnectionString>);
}
```
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论