找到了多个名为 'NewProject.Models.DbContext' 的 DbContext 通过使用精确大小写的完全限定名称指定要使用的一个

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

我正在使用 Asp.Net Core 2.1 开发 Web 应用程序。在我使用脚手架添加新身份后,它为我生成了这些代码:

代码生成于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>();               

            });

        }
    }
}

代码生成于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?}");
                });                
            }   
        }
    }

在我想使用 EF 搭建一个带有控制器和视图的模型之前,它一直运行良好。设置所有内容并单击“确定”时,我收到一条错误消息:找到多个名为 'ShareAndCare.Models.ShareAndCareContext' 的 DbContext。通过使用确切大小写的完全限定名称来指定要使用的名称。 我检查了所有文件夹和名称空间,但那里没有问题,只有一个上下文具有该名称。那么问题出在哪里?

我把问题和答案留在这里,这样人们就不会像我一样疯狂地手动寻找所有可能的解决方案。我发现在 IdentityHostingStartup.cs 的 Configure 方法中添加上下文导致了问题。我更改了将上下文添加到 Startup.cs 的 Configure 方法的位置,它工作得很好。

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

我刚刚删除了 2 个文件:

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

这修正了错误!

在我的案例中,我添加了 services.AddDbContext<DBContext> 但我的 DBContext 名称是

ApplicationDBContext.

在 Startup.cs 中更改了我的名字并且成功了

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

希望这对某人有所帮助:)