Ibanez1408
Ibanez1408

Reputation: 5048

More than one DbContext was found

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."

How can this be resolved?

Upvotes: 47

Views: 127918

Answers (12)

Muhammad Tanveer
Muhammad Tanveer

Reputation: 11

The issue occurred because I was using the same database name for multiple DbContext classes within the same solution. Here's an example of my connection string configuration:

  "ConnectionStrings": {
    "DefaultConnection": "Server=MTANVEER\\SQLEXPRESS;Database=StockifyDb;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;"
  }

Upvotes: 1

Steve Shahbazi
Steve Shahbazi

Reputation: 175

What worked for me when having more than one DbContext is that you need to introduce all of them in the Program.cs. For example, I have two DbContext namely ApplicationDbContext and LibraryDbContext so I need to do:

// Register the DbContext and configure the connection string
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddDbContext<LibraryDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Also, remember when using Package Manager Console in Visual Studio or any command line:

dotnet ef add-migration AddingBooksAuthors --context BookLibrary.Data.LibraryDbContext --project .\BookLibrary

where AddingBooksAuthors is my comment, I specifically picked the DbContext I want to use and then specified the associated project.

Upvotes: 0

Ahmed Saied
Ahmed Saied

Reputation: 271

Specify DbContext after migration name, message guided you to use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.

for cmd:

dotnet ef migrations add InitialCreate --context DataContext

for PowerShell:

dotnet ef migrations add InitialCreate -context DataContext

Upvotes: 0

sweetnandha cse
sweetnandha cse

Reputation: 951

for Mac os in visual studio i did like this. its working

dotnet ef database update -c ApplicationDbContext

Upvotes: 2

aseman arabsorkhi
aseman arabsorkhi

Reputation: 362

When We have more than one DbContext class which is inherited from DbContext ,for evrey one Like PrsWebAppContext class

public class PrsWebAppContext : DbContext

we can write:

NameSpace:PrsWebApp.Data

ClassName:PrsWebAppContext

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

Build started... Build succeeded.

For More information please refer to :

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

Upvotes: 4

Olorunfemi Davis
Olorunfemi Davis

Reputation: 1090

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.

Upvotes: 2

maximelian1986
maximelian1986

Reputation: 2452

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

Upvotes: 72

ios_dotnet_superuser
ios_dotnet_superuser

Reputation: 304

update-database -Context YourContext

Upvotes: 10

MK Hasan
MK Hasan

Reputation: 11

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

Upvotes: 1

&#214;mer
&#214;mer

Reputation: 188

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

Upvotes: 0

themefield
themefield

Reputation: 4235

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

[--context | -c]

The DbContext class to use. Class name only or fully qualified with namespaces. If this option is omitted, EF Core will find the context class. If there are multiple context classes, this option is required.

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

Upvotes: 6

Daleman
Daleman

Reputation: 874

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

Upvotes: 14

Related Questions