简体   繁体   中英

More than one DbContext named 'NewProject.Models.DbContext' was found Specify which one to use by providing its fully qualified name using exact case

I was developing a Web-App with Asp.Net Core 2.1. After I added the new identity with scaffolder it generated me these codes:

Code generated in IdentityStartup.cs

[assembly:HostingStartup(typeof(ShareAndCare.Areas.Identity.IdentityHostingStartup))]
namespace ShareAndCare.Areas.Identity
{
    public class IdentityHostingStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureServices((context, services) => {

                services.AddDbContext<ShareAndCareContext>(options =>
                   options.UseLazyLoadingProxies().UseSqlServer(
                       context.Configuration.GetConnectionString("ShareAndCareContextConnection")));

                services.AddIdentity<ShareAndCareUser, IdentityRole>()
                .AddEntityFrameworkStores<ShareAndCareContext>()
                .AddDefaultTokenProviders();

                services.AddSingleton<IEmailSender, EmailSender>();               

            });

        }
    }
}

Code generated in Startup.cs

    namespace ShareAndCare
    {
        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.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });            

                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, IServiceProvider serviceProvider)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }

                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseAuthentication();
                app.UseCookiePolicy();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });                
            }   
        }
    }

This was working fine until I wanted to scaffold a model with controller and views using EF. When set up everything and click ok I was getting an error saying: More than one DbContext named 'ShareAndCare.Models.ShareAndCareContext' was found. Specify which one to use by providing its fully qualified name using its exact case. I checked all the folders and namespaces but there was no problem there, there was only one context with that name. So what was the problem?

I'm leaving that question and answer here so people don't go crazy looking for all possible solutions manually like I did. I found out that adding the context in the Configure method of IdentityHostingStartup.cs was causing the problem. I changed the place where I added the context to the Configure method of Startup.cs and it was working just fine.

namespace ShareAndCare
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });            

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext<ShareAndCareContext>(options =>
                   options.UseLazyLoadingProxies().UseSqlServer(
                       Configuration.GetConnectionString("ShareAndCareContextConnection")));

        }

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

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });                
        }   
    }
}

I just deleted the 2 files:

  1. Areas/Identity/Data/APNameIdentityDbContext.cs and
  2. Areas/Identity/IdentityHostingStartup.cs

This fixed the error!

In my Case I was adding services.AddDbContext<DBContext> but instead my DBContext name was

ApplicationDBContext .

Changed my Name in Startup.cs and it worked

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(Configuration["Data:ConnectionStrings:DefaultConnection"]));
        }

Hope this helps someone :)

You just need to Delete One File and it works perfectly

Go to your Project directory

YOUR PROJECT/Areas/Identity/Data/APNameIdentityDbContext.cs

Just Remove it and do migration

  1. add-migration init
  2. Update-database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM