Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 432
brainoverflow98 Avatar asked Jul 13 '18 05:07

brainoverflow98


People also ask

Can I have more than one DbContext?

Multiple DbContext was first introduced in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases.

Is DbContext Singleton or scoped?

DbContext in dependency injection for ASP.NET Core This example registers a DbContext subclass called ApplicationDbContext as a scoped service in the ASP.NET Core application service provider (a.k.a. the dependency injection container).

What is a DbContext?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.


1 Answers

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?}");
            });                
        }   
    }
}
like image 164
brainoverflow98 Avatar answered Sep 21 '22 12:09

brainoverflow98