C# and Entity Framework Core v7.0.2 code-first – DbContext database provider error during migration Initialization

huangapple go评论79阅读模式
英文:

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策略初始化我的数据库。

但是当我运行以下命令时:

  1. dotnet ef migrations add InitialCreate --project PreventionCyber.DAL --startup-project PreventionCyber.Web

我遇到了以下错误:

  1. System.InvalidOperationException: 为此DbContext未配置数据库提供程序。可以通过覆盖“DbContext.OnConfiguring”方法或在应用程序服务提供程序上使用“AddDbContext”来配置提供程序。如果使用“AddDbContext”,还请确保您的DbContext类型在其构造函数中接受DbContextOptions<TContext>对象,并将其传递给DbContext的基构造函数。

PCDbContext.cs

  1. using Microsoft.EntityFrameworkCore.ChangeTracking;
  2. using Microsoft.EntityFrameworkCore;
  3. using PreventionCyber.DAL.Common;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace PreventionCyber.DAL.Context
  10. {
  11. public class PCDbContext : DbContext
  12. {
  13. public PCDbContext()
  14. {
  15. }
  16. public PCDbContext(DbContextOptions<PCDbContext> options): base(options)
  17. {
  18. }
  19. protected override void OnModelCreating(ModelBuilder modelBuilder)
  20. {
  21. foreach (var entity in modelBuilder.Model.GetEntityTypes())
  22. {
  23. // Renommage clé primaire
  24. entity.GetProperty("Id")
  25. ?.SetColumnName($"{entity.ClrType.Name}Id");
  26. }
  27. }
  28. public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  29. {
  30. OnBeforeSaving();
  31. return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
  32. }
  33. private void OnBeforeSaving()
  34. {
  35. var entries = ChangeTracker.Entries();
  36. foreach (var entry in entries)
  37. {
  38. if (entry.Entity is BaseEntity trackable)
  39. {
  40. var now = DateTime.UtcNow;
  41. var user = GetCurrentUser();
  42. switch (entry.State)
  43. {
  44. case EntityState.Modified:
  45. trackable.ModifieLe = now;
  46. trackable.ModifiePar = user;
  47. break;
  48. case EntityState.Added:
  49. trackable.CreeLe = now;
  50. trackable.CreePar = user;
  51. trackable.ModifieLe = now;
  52. trackable.ModifiePar = user;
  53. break;
  54. }
  55. }
  56. }
  57. }
  58. private string GetCurrentUser()
  59. {
  60. return "UserName"; // TODO implement your own logic
  61. // If you are using ASP.NET Core, you should look at this answer on StackOverflow
  62. // https://stackoverflow.com/a/48554738/2996339
  63. }
  64. }
  65. }

Program.cs

  1. using Microsoft.EntityFrameworkCore;
  2. using PreventionCyber.DAL.Context;
  3. var builder = WebApplication.CreateBuilder(args);
  4. // 将服务添加到容器中
  5. builder.Services.AddControllersWithViews();
  6. var app = builder.Build();
  7. builder.Services.AddDbContext<DbContext, PCDbContext>(options
  8. => options.UseSqlServer(builder.Configuration.GetValue<string>("ConnectionStrings:PreventionCyber")));
  9. // 配置HTTP请求管道
  10. if (!app.Environment.IsDevelopment())
  11. {
  12. app.UseExceptionHandler("/Home/Error");
  13. // 默认的HSTS值是30天。您可能需要根据生产场景进行更改,参见 https://aka.ms/aspnetcore-hsts。
  14. app.UseHsts();
  15. }
  16. app.UseHttpsRedirection();
  17. app.UseStaticFiles();
  18. app.UseRouting();
  19. app.UseAuthorization();
  20. app.MapControllerRoute(
  21. name: "default",
  22. pattern: "{controller=Home}/{action=Index}/{id?}");
  23. 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:

  1. 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

  1. using Microsoft.EntityFrameworkCore.ChangeTracking;
  2. using Microsoft.EntityFrameworkCore;
  3. using PreventionCyber.DAL.Common;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace PreventionCyber.DAL.Context
  10. {
  11. public class PCDbContext : DbContext
  12. {
  13. public PCDbContext()
  14. {
  15. }
  16. public PCDbContext(DbContextOptions&lt;PCDbContext&gt; options): base(options)
  17. {
  18. }
  19. protected override void OnModelCreating(ModelBuilder modelBuilder)
  20. {
  21. foreach (var entity in modelBuilder.Model.GetEntityTypes())
  22. {
  23. // Renommage cl&#233; primaire
  24. entity.GetProperty(&quot;Id&quot;)
  25. ?.SetColumnName($&quot;{entity.ClrType.Name}Id&quot;);
  26. }
  27. }
  28. public override Task&lt;int&gt; SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  29. {
  30. OnBeforeSaving();
  31. return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
  32. }
  33. private void OnBeforeSaving()
  34. {
  35. var entries = ChangeTracker.Entries();
  36. foreach (var entry in entries)
  37. {
  38. if (entry.Entity is BaseEntity trackable)
  39. {
  40. var now = DateTime.UtcNow;
  41. var user = GetCurrentUser();
  42. switch (entry.State)
  43. {
  44. case EntityState.Modified:
  45. trackable.ModifieLe = now;
  46. trackable.ModifiePar = user;
  47. break;
  48. case EntityState.Added:
  49. trackable.CreeLe = now;
  50. trackable.CreePar = user;
  51. trackable.ModifieLe = now;
  52. trackable.ModifiePar = user;
  53. break;
  54. }
  55. }
  56. }
  57. }
  58. private string GetCurrentUser()
  59. {
  60. return &quot;UserName&quot;; // TODO implement your own logic
  61. // If you are using ASP.NET Core, you should look at this answer on StackOverflow
  62. // https://stackoverflow.com/a/48554738/2996339
  63. }
  64. }
  65. }

Program.cs

  1. using Microsoft.EntityFrameworkCore;
  2. using PreventionCyber.DAL.Context;
  3. var builder = WebApplication.CreateBuilder(args);
  4. // AddAsync services to the container.
  5. builder.Services.AddControllersWithViews();
  6. var app = builder.Build();
  7. builder.Services.AddDbContext&lt;DbContext, PCDbContext&gt;(options
  8. =&gt; options.UseSqlServer(builder.Configuration.GetValue&lt;string&gt;(&quot;ConnectionStrings:PreventionCyber&quot;)));
  9. // Configure the HTTP request pipeline.
  10. if (!app.Environment.IsDevelopment())
  11. {
  12. app.UseExceptionHandler(&quot;/Home/Error&quot;);
  13. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  14. app.UseHsts();
  15. }
  16. app.UseHttpsRedirection();
  17. app.UseStaticFiles();
  18. app.UseRouting();
  19. app.UseAuthorization();
  20. app.MapControllerRoute(
  21. name: &quot;default&quot;,
  22. pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);
  23. app.Run();

I don't understand the error because I've already defined a constructor using DbContextOptions&lt;TContext&gt; 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.

  1. protected override void OnConfiguring(DbContextOptionsBuilder options)
  2. {
  3. options.UseSqlServer(&lt;yourConnectionString&gt;);
  4. }
英文:

The error suggested you may need to add the OnConfiguring override method to the PCDbContext class.

  1. protected override void OnConfiguring(DbContextOptionsBuilder options)
  2. {
  3. options.UseSqlServer(&lt;yourConnectionString&gt;);
  4. }
  5. ```
  6. </details>

huangapple
  • 本文由 发表于 2023年2月14日 04:03:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定