【问题标题】:Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time无法创建“AppDbContext”类型的对象。对于设计时支持的不同模式
【发布时间】:2020-06-30 11:57:18
【问题描述】:

我有一个带有 netcoreapp3.0 的项目,使用实体框架,一切正常,直到它停止,所以我决定通过创建一个新项目来重新创建项目,并手动创建类并在其中复制/粘贴(更改命名空间当然)。

新项目是netcoreapp3.1,我试图通过添加将新表添加到数据库中:

  public DbSet<UsersCredentialsModel> UsersCredentialsModels { get; set; }

到 AppDbContext 类,但运行时它不会添加它并给出错误。

我通过转到 Sql Server 对象 exp 并单击删除来删除数据库。 我删除了迁移文件夹。

当我尝试添加迁移“名称”时 我明白了

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: One or more errors occurred. (Failure occurred during job recovery.)

无法创建“AppDbContext”类型的对象。有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728

这里是项目中的 sn-ps:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Models;

namespace DatabaseContext
{
    public class AppDbContext : IdentityDbContext<ApplicationUser>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<Message>().Property(m => m.Service).HasConversion<int>();
            builder.Entity<ApplicationUser>().HasMany<Message>(m => m.Messages).WithOne(u => u.User).IsRequired();
            base.OnModelCreating(builder);
        }


        public DbSet<Message> Messages { get; set; }
        public DbSet<UsersCredentialsModel> UsersCredentialsModels { get; set; }
    }
}

以及ConfigureServices的启动方法:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddIdentity<ApplicationUser, IdentityRole>(options => options.User.AllowedUserNameCharacters = null).AddEntityFrameworkStores<AppDbContext>();
        services.AddControllersWithViews();
        services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("AutoLoverDbConnection"),x => x.MigrationsAssembly("AutoMatcherProject")));
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddTransient<ISche, SchedulerImpl>();
        services.AddTransient<IQueue, QueueImpl>();
        services.AddTransient<SchedulerJob>();
        services.AddTransient<IBotFactory,BotFactory>();
        //services.AddTransient<ICredentialSaver, CredentialSaver.CredentialSaver>();
        services.AddSingleton(provider => _scheduler);
        services.AddAuthentication().AddFacebook(options => {
            options.AppId = "";
            options.AppSecret = "";
            options.SaveTokens = true;
        });
        _scheduler.Clear();
    }

编辑:

在运行 add-migration "name" -verbose 我得到的堆栈跟踪之后:

 System.NullReferenceException: Object reference not set to an instance of an object.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Object reference not set to an instance of an object.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'AppDbContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.MissingMethodException: No parameterless constructor defined for type 'AutoMatcherProject1.Models.AppDbContext'.
   at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

有趣的是,它使用当前构造函数在较旧的项目上工作,所以我不知道有什么问题.. 搜索了互联网,但没有任何帮助,我将不胜感激!

【问题讨论】:

    标签: asp.net-core entity-framework-core asp.net-core-mvc


    【解决方案1】:

    在我的例子中,我做了一些步骤并且迁移成功了,我不知道如何,但我所做的是在启动时添加迁移程序集

    public void ConfigureServices(IServiceCollection services)
    {
          services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
    x => x.MigrationsAssembly("MyMigrationAssemblyProjectName")));
    }
    

    然后我将有startup.cs的项目设置为启动项目,并添加了迁移,所以它要求我添加包

    Microsoft.EntityFrameworkCore.Design
    

    安装包后,我运行迁移,它让我选择迁移程序集的项目,我选择了它,它工作,我不确定哪个步骤完全解决了问题,但它最终工作了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多