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

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

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&lt;PCDbContext&gt; options): base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            foreach (var entity in modelBuilder.Model.GetEntityTypes())
            {
                // Renommage cl&#233; primaire
                entity.GetProperty(&quot;Id&quot;)
                    ?.SetColumnName($&quot;{entity.ClrType.Name}Id&quot;);
            }
        }

        public override Task&lt;int&gt; 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 &quot;UserName&quot;; // 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&lt;DbContext, PCDbContext&gt;(options
    =&gt; options.UseSqlServer(builder.Configuration.GetValue&lt;string&gt;(&quot;ConnectionStrings:PreventionCyber&quot;)));

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler(&quot;/Home/Error&quot;);
    // 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: &quot;default&quot;,
    pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);
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.

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

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

        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(&lt;yourConnectionString&gt;);
        }
    ```

</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:

确定