无法在Entity Framework Core中迁移DbContext类

问题描述 投票:0回答:1

我现在正在使用ASP.NET核心web api开发web api。这是我第一次使用ASP.NET核心。我是一名ASP.NET MVC开发人员。但是有一段时间了。我现在正在做的是为运行迁移命令的Entity Framework创建一个DbContext类。但我正在使用三个不同的项目来分离逻辑。

这是我的项目结构:

[![在此输入图片说明] [1]] [1]

我安装了以下包。

Install-Package Microsoft.EntityFrameworkCore.SqlServer  -Projectname thegoodyard.api
Install-Package Microsoft.EntityFrameworkCore.Tools  -Projectname thegoodyard.api
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design  -Projectname thegoodyard.api
Install-Package Microsoft.EntityFrameworkCore.SqlServer  -Projectname thegoodyard.domain
Install-Package Microsoft.EntityFrameworkCore.Tools  -Projectname thegoodyard.domain
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design  -Projectname thegoodyard.domain

thegoodyard.domain项目中,我创建了一个名为ThegoodyardContext.cs的DB上下文类,其定义如下。

namespace thegoodyard.domain.Concrete
{
    public virtual DbSet<Category> Categories { get; set; }

    public partial class ThegoodyardContext: DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if(!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(@"Server=(localdb)\\mssqllocaldb;Database=ThegoodyardContext;Trusted_Connection=True; MultipleActiveResultSets=true");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }
    }
}

然后在Thegoodyard.api项目中,在ConfigureServices类的StartUp方法中,我注册了这样的上下文:

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc();

     services.AddDbContext<thegoodyard.domain.Concrete.ThegoodyardContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("ThegoodyardContext")));
}

然后我启用了运行以下命令的迁移

enable-migration -projectname thegoodyard.api

但它说,命令太旧了,请改用add-migration。我改用了这个。

add-migration CreateCategory

然后我收到以下错误

在“Program”类上访问IWebHost时发生错误。继续没有应用程序服务提供商。错误:使用配置调用AddDbContext,但上下文类型'ThegoodyardContext'仅声明无参数构造函数。这意味着永远不会使用传递给AddDbContext的配置。如果配置传递给AddDbContext,那么'ThegoodyardContext'应该声明一个接受DbContextOptions的构造函数,并且必须将它传递给DbContext的基础构造函数。

在程序集'thegoodyard.api'中找不到DbContext。确保您使用的是正确的程序集,并且该类型既不是抽象的也不是通用的。

我该如何解决?

asp.net asp.net-core entity-framework-core
1个回答
1
投票

打开包管理器控制台

默认项目:“选择您的图层名称”,如:thegoodyard.domain then

Enable-Migrations

请检查此链接http://www.entityframeworktutorial.net/code-first/code-based-migration-in-code-first.aspx

© www.soinside.com 2019 - 2024. All rights reserved.