无法创建“ AppDbContext”类型的对象。针对设计时支持的不同模式

时间:2020-03-19 10:50:37

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

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

新项目是netcoreapp3.1,我正在尝试通过添加新表到数据库:

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

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

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

当我尝试添加迁移“名称”时 我得到

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

以下是该项目的摘要:

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();
    }

enter image description here

编辑:

运行add-migration“ name”之后-详细说明我得到的堆栈跟踪:

 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)

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

1 个答案:

答案 0 :(得分:0)

就我而言,我做了一些步骤,迁移工作正常,我不知道如何做,但是我要做的是在启动中添加迁移程序集

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

然后我将具有startup.cs的项目设置为启动项目,并添加了迁移,因此它要求我添加软件包

Microsoft.EntityFrameworkCore.Design

安装该软件包后,我运行迁移,它要求我选择迁移程序集的项目,我选择了它,然后它起作用了,我不确定哪一步可以完全解决问题,但最终还是可以起作用