找到多个DbContext

时间:2018-09-13 09:48:32

标签: c# asp.net-core

我正在使用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迁移添加了InitialCreate”,我收到此错误:“找到了多个DbContext。指定要使用的DbContext。对PowerShell命令使用'-Context'参数,对' --context'代表dotnet命令。” 您能帮我解决这个问题吗?谢谢!

8 个答案:

答案 0 :(得分:2)

dotnet ef migrations add <your_migration_name> -c <your_context_class_name>

[-上下文| -c]

要使用的DbContext类。仅类别名称或完全符合以下条件的类别名称 命名空间。如果忽略此选项,EF Core将查找上下文 类。如果存在多个上下文类,则需要此选项。

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

答案 1 :(得分:1)

似乎从DbContext类继承了几个类(可能带有一些nuget包)。因此,使用

添加迁移
Add-Migration MyMigration --context DataContext

答案 2 :(得分:0)

请遵循this syntax

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

在您的情况下

add-migration MyMigration -Context DataContext

答案 3 :(得分:0)

当数据库项目中的DbContext超过1个时, 用于从我的项目中的PrsWebAppContext之类的DbContext继承的evrey类

公共类PrsWebAppContext:DbContext

我们可以按照我在下面说的来写:

NameSpace:PrsCarsWebApp.Data ClasName:CarsWebAppContext

PM> add-migration initial -context PrsCarsWebApp.Data.CarsWebAppContext

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

有关更多信息,请参阅:

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

答案 4 :(得分:0)

如果您已经创建了迁移,但是仍然给出了数据库更新命令错误,那么此命令将有助于解决该问题

dotnet ef数据库更新-p基础结构-s API --context StoreContext

答案 5 :(得分:0)

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

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);
        }
    }

答案 6 :(得分:0)

//错误代码:

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

//正确的代码

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

此外,YourContextClassName 应继承 DbContext,但您将其命名为 DbContext。

这个问题很老了,但我的回答很重要,因为我在将项目从 MySQL 迁移到 SQLServer 时遇到了同样的问题。

答案 7 :(得分:0)

update-database -Context YourContext
相关问题