【问题标题】:.net core Migration error: Unable to create an object of type 'DataContext'.net core 迁移错误:无法创建“DataContext”类型的对象
【发布时间】:2021-02-22 11:52:54
【问题描述】:

我尝试使用单独的项目设置 dotnet 后端,我将 API 项目(它是一个 webapi)作为主项目,然后我有包含 DataContext 类的持久性项目。

DataContext.cs:

using Domain;
using Microsoft.EntityFrameworkCore;

namespace Persistence
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions options) : base(options)
        {

        }
        public DbSet<Book> Books { get; set; }
    }
}

我将 DataContext 注入到启动文件中的配置服务中:

   public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(opt =>
            {
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddControllers();
        }

然后当我尝试使用此命令添加迁移时:

dotnet ef migrations add InitialCreate -s API -p Persistence    

它给了我这个错误。

请知道为什么会这样吗?

【问题讨论】:

  • 除了“我无法制作对象”之外,还有更多的错误信息吗?
  • @gunr2171 这是完整的错误:无法创建“DataContext”类型的对象。有关设计时支持的不同模式,请参阅go.microsoft.com/fwlink/?linkid=851728
  • 从您发布的链接中:“DbContext 本身及其构造函数中的任何依赖项都需要在应用程序的服务提供程序中注册为服务。这可以通过在 DbContext 上使用一个构造函数来轻松实现DbContextOptions 的实例作为参数并使用 AddDbContext 方法。”尝试这样做 - 在您的构造函数中创建参数DbContextOptions&lt;DataContext&gt; options
  • @gunr2171 我就是这样做的:public DataContext(DbContextOptions&lt;DataContext&gt; options) : base(options) { } 不幸的是它仍然给出了同样的错误

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


【解决方案1】:

首先检查 appsettings.json 中的连接字符串,然后 运行此命令进行迁移

dotnet ef migrations add 1

然后

dotnet ef migrations update

如果不起作用,请检查 *.csproject 中的 ef 核心包

【讨论】:

    【解决方案2】:

    尝试添加一个空的构造函数:

    公共 DataContext(){}

    【讨论】:

    • 我这样做了,现在它给了我一个不同的错误: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&lt;TContext&gt; object in its constructor and passes it to the base constructor for DbContext.
    • 尝试像这样覆盖 Context 上的 OnConfiguring 方法:protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("your connection string goes here") ; } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 2020-08-22
    • 2023-02-16
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多