Невозможно создать объект типа «AppDbContext». Для разных шаблонов, поддерживаемых во время разработки - PullRequest
0 голосов
/ 19 марта 2020

У меня был проект с netcoreapp3.0, использующий Entity Framework, все работало, пока он не остановился, поэтому я решил заново создать проект, создав новый проект и вручную создав классы и скопировав / вставив внутри (изменяя пространства имен ofcourse).

новый проект - netcoreapp3.1, я пытался добавить новую таблицу в базу данных, добавив:

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

в класс AppDbContext, но при запуске он не не добавил его и выдал ошибки.

Я удалил базу данных, перейдя к Sql Объект сервера 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

Вот фрагменты проекта:

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 = "2975433209152858";
            options.AppSecret = "61a40260163846bab0672bbf5bf6c8a8";
            options.SaveTokens = true;
        });
        _scheduler.Clear();
    }

enter image description here

РЕДАКТИРОВАТЬ:

после запуска add -igration "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)

забавно то, что он работал над старым проектом с текущим конструктором, так что я не знаю, в чем проблема .. искал inte rnet но ничего не помогает, я был бы признателен за все!

...