More than one DbContext was found

Viewed 65143

I am implementing a code first database using AspCore 2. I have a "DataContext.cs" that goes like this:

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

and this in my "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();
    }
}

When I try running the dotnet migration, dotnet ef migrations add InitialCreate I get the following error:

"More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands."

Can you please help me make this right? Thank you!

8 Answers

It looks like there are several classes that have been inherited from DbContext class (may have come from some NuGet package). So add migration with

Add-Migration MyMigration -context DataContextName

please follow this syntax

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

in your case,

add-migration MyMigration -Context DataContext
update-database -Context YourContext

When We have more than 1 DbContext in Database project , for evrey Class which is inherited from DbContext Like PrsWebAppContext in my project

public class PrsWebAppContext : DbContext

we can write as I Said below :

NameSpace:PrsCarsWebApp.Data ClasName:CarsWebAppContext

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

Build started... Build succeeded.

For More information please refer to :

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

Wrong code:

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

Right code

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

Also, YourContextClassName should inherit DbContext but you named it DbContext.

This question is pretty old but my answer is relevant as I encountered the same while moving a project from MySQL to SQLServer.

If any of you already have migrations created but still it gives the error on database update command then this command can be helpful to solve it

dotnet ef database update -p Infrastructure -s API --context StoreContext

First of all solve this problem by adding migration. So add migration with:

Add-Migration MyMigration -context DataContext

if you are not able to solve this problem from now or Still facing a problem when add a new controller then add following code portion in your DB context:

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