42

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?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Ibanez1408
  • 4,550
  • 10
  • 59
  • 110

9 Answers9

63

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
Dennis VW
  • 2,977
  • 1
  • 15
  • 36
maximelian1986
  • 2,308
  • 1
  • 18
  • 32
  • I even tried this => dotnet ef migrations add InitialCreate --ConfigurationTypeName [DatingApp.API].Migrations.DataContext.Configuration but I get the error of Unrecognized option "-ConfiguaritonTypeName" – Ibanez1408 Sep 13 '18 at 10:12
  • 3
    Use `dotnet ef migrations add InitialCreate --context DataContext` – poke Sep 13 '18 at 10:23
  • 1
    @Ibanez1408 it should be `dotnet ef migrations add InitialCreate -ConfigurationTypeName DatingApp.API.Migrations.DataContext.Configuration`. One '-' less. I also removed the braces, never saw that syntax .. might work though. – nilsK Sep 13 '18 at 10:32
  • The DatingApp.API is one word. I enclosed it in brackets – Ibanez1408 Sep 13 '18 at 10:51
  • I get this error => ``Unrecognized option '-ConfigurationTypeName' – Ibanez1408 Sep 13 '18 at 15:45
  • 1
    There’s no `ConfigurationTypeName` option, I really don’t know where you took that from… Run `dotnet ef migrations add --help` for usage information. – poke Sep 13 '18 at 21:40
11

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
Daleman
  • 794
  • 8
  • 23
  • This syntax worked for me in the Package Manager Console, I had to also specify the project because I believe PMC was targeting the wrong one. `add-migration MyMigration -context MyDbContext -project MyDatabaseProject` – TechnoCore May 27 '20 at 22:01
  • 1
    Thanks! Worked perfectly! – Vasilije Bursac Dec 14 '20 at 18:44
6
update-database -Context YourContext
janw
  • 8,758
  • 11
  • 40
  • 62
  • 2
    You might want to extend your answer and explain how this command solves the problem – BDL May 04 '21 at 09:37
5
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

themefield
  • 3,847
  • 30
  • 32
2

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.

Arsman Ahmad
  • 2,000
  • 1
  • 26
  • 34
Olorunfemi Davis
  • 1,001
  • 10
  • 23
1

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

1

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

dotnet ef database update -c ApplicationDbContext
sweetnandha cse
  • 705
  • 7
  • 16
0

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

Ömer
  • 188
  • 2
  • 11
0

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);
        }
    }
MK Hasan
  • 1
  • 1