发现多个DbContext

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

我正在使用 AspCore 2 实现代码优先数据库。我有一个“DataContext.cs”,如下所示:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string MiddelName { get; set; }
    public string LastName { get; set; }
    public bool IsActive { get; set; }
    public DateTime? DateAdded { get; set; }
}

public class DataContext : IdentityDbContext<ApplicationUser>
{
    public DataContext(DbContextOptions<DataContext> options) : base(options) {}

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
             base.OnModelCreating(modelBuilder);

          //AspNetUsers -> User
        modelBuilder.Entity<ApplicationUser>()
            .ToTable("User");
        //AspNetRoles -> Role
        modelBuilder.Entity<IdentityRole>()
            .ToTable("Role");
        //AspNetUserRoles -> UserRole
        modelBuilder.Entity<IdentityUserRole>()
            .ToTable("UserRole");
        //AspNetUserClaims -> UserClaim
        modelBuilder.Entity<IdentityUserClaim>()
            .ToTable("UserClaim");
        //AspNetUserLogins -> UserLogin
        modelBuilder.Entity<IdentityUserLogin>()
            .ToTable("UserLogin");
    }
}

这在我的“startup.cs”中

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

当我尝试运行 dotnet 迁移时,

dotnet ef migrations add InitialCreate
我收到以下错误:

“发现了多个 DbContext。指定要使用哪一个。对于 PowerShell 命令使用“-Context”参数,对于 dotnet 命令使用“--context”参数。”

如何解决这个问题?

c# asp.net-core entity-framework-core dbcontext
10个回答
66
投票

看起来有几个类继承自 DbContext 类(可能来自某些 NuGet 包)。所以添加迁移

Add-Migration MyMigration -context DataContextName

13
投票

请遵循此语法

Add-Migration [-Name] <String> [-OutputDir <String>] [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>]

就你而言,

add-migration MyMigration -Context DataContext

6
投票
dotnet ef migrations add <your_migration_name> -c <your_context_class_name>

[--上下文 | -c]

要使用的 DbContext 类。仅类名或完全限定 命名空间。如果省略此选项,EF Core 将查找上下文 班级。如果有多个上下文类,则需要此选项。

来自 https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet#common-options


6
投票
update-database -Context YourContext

3
投票

当我们有多个从 DbContext 继承的 DbContext 类时,每一个都像 PrsWebAppContext 类

公共类PrsWebAppContext:DbContext

我们可以写:

名称空间:PrsWebApp.Data

类名:PrsWebAppContext

PM> add-migration initial -context PrsWebApp.Data.PrsWebAppContext

构建开始... 构建成功。

更多信息请参考:

https://www.youtube.com/watch?v=YMBAeHaqrVs


2
投票

错误代码:

services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

正确代码

services.AddDbContext<YourContextClassName>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

此外,

YourContextClassName
应该继承
DbContext
,但你将其命名为
DbContext

这个问题很老了,但我的答案是相关的,因为我在将项目从

MySQL
移动到
SQLServer
时遇到了同样的问题。


2
投票

对于 Visual Studio 中的 Mac 操作系统,我确实喜欢这样。它的工作原理

dotnet ef database update -c ApplicationDbContext

1
投票

首先通过添加迁移来解决这个问题。因此添加迁移:

Add-Migration MyMigration -context DataContext

如果您现在无法解决此问题或在添加新控制器时仍然遇到问题,请在数据库上下文中添加以下代码部分:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var connectionString = configuration.GetConnectionString("AppDBContextConnection");

            optionsBuilder.UseSqlServer(connectionString);
        }
    }

0
投票

如果你们中的任何人已经创建了迁移,但仍然在数据库更新命令上给出错误,那么此命令可以帮助解决它

dotnet ef 数据库更新 -p 基础设施 -s API --context 商店上下文


0
投票

在迁移名称后指定 DbContext,消息引导您使用 PowerShell 命令的“-Context”参数和 dotnet 命令的“--context”参数。

dotnet ef migrations add InitialCreate --context DataContext
© www.soinside.com 2019 - 2024. All rights reserved.