«ApplicationDbContext» не наследуется от DbContext

Я получаю эту ошибку:

Тип ApplicationDbContext не наследуется от DbContext. Для свойства DbMigrationsConfiguration.ContextType должен быть задан тип, наследуемый от DbContext.

Это мой код:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
//using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace Manufactura.Models
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {

        }

        public DbSet<Categories> Categories { get; set; }
        public DbSet<CustomerCities> CustomerCities { get; set; }
        public DbSet<CustomerCountries> CustomerCountries { get; set; }
        public DbSet<CustomerRegions> CustomerRegions { get; set; }
        public DbSet<Customers> Customers { get; set; }
        public DbSet<Employees> Employees { get; set; }
        public DbSet<Payments> Payments { get; set; }
        public DbSet<ProductDetails> ProductDetails { get; set; }
        public DbSet<ProductionOrders> ProductionOrders { get; set; }
        public DbSet<Products> Products { get; set; }
        public DbSet<RawMaterials> RawMaterials { get; set; }
        public DbSet<SaleInvoices> SaleInvoices { get; set; }
        public DbSet<Shippings> Shippings { get; set; }
        public DbSet<SuplierCities> SuplierCities { get; set; }
        public DbSet<SuplierCountries> SuplierCountries { get; set; }
        public DbSet<SuplierInvoices> SuplierInvoices { get; set; }
        public DbSet<SuplierRegions> SuplierRegions { get; set; }
        public DbSet<Supliers> Supliers { get; set; }
        

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // optionsBuilder.UseSqlServer(@"Server=.\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;");

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Categories>().HasKey(m => m.CategoryId);
            modelBuilder.Entity<CustomerCities>().HasKey(m => m.CustomerCity);
            modelBuilder.Entity<CustomerCountries>().HasKey(m => m.CustomerCountry);
            modelBuilder.Entity<CustomerRegions>().HasKey(m => m.CustomerRegion);
            modelBuilder.Entity<Customers>().HasKey(m => m.CustomerId);
            modelBuilder.Entity<Employees>().HasKey(m => m.EmployeeId);
            modelBuilder.Entity<Payments>().HasKey(m => m.PaymentId);
            modelBuilder.Entity<ProductDetails>().HasKey(m => m.ProductDetailsId);
            modelBuilder.Entity<ProductionOrders>().HasKey(m => m.ProductionOrdersId);
            modelBuilder.Entity<Products>().HasKey(m => m.ProductId);
            modelBuilder.Entity<RawMaterials>().HasKey(m => m.RawMaterialsId);
            modelBuilder.Entity<SaleInvoices>().HasKey(m => m.SaleInvoiceId);
            modelBuilder.Entity<Shippings>().HasKey(m => m.ShippingId);
            modelBuilder.Entity<SuplierCities>().HasKey(m => m.SuplierCity);
            modelBuilder.Entity<SuplierCountries>().HasKey(m => m.SuplierCountry);
            modelBuilder.Entity<SuplierInvoices>().HasKey(m => m.SuplierInvoiceId);
            modelBuilder.Entity<SuplierRegions>().HasKey(m => m.SuplierRegion);
            modelBuilder.Entity<Supliers>().HasKey(m => m.SuplierId);

            modelBuilder.Entity<Products>()
            .HasOne(p => p.Category)
            .WithMany(b => b.Products);

            modelBuilder.Entity<CustomerRegions>()
           .HasOne(p => p.CustomerCountry)
           .WithMany(b => b.CustomerRegions);

            modelBuilder.Entity<CustomerCities>()
           .HasOne(p => p.CustomerRegion)
           .WithMany(b => b.CustomerCities);

            modelBuilder.Entity<Customers>()
           .HasOne(p => p.CustomerCity)
           .WithMany(b => b.Customers);

            modelBuilder.Entity<SaleInvoices>()
           .HasOne(p => p.Customer)
           .WithMany(b => b.SaleInvoices);

            modelBuilder.Entity<Payments>()
           .HasOne(p => p.SaleInvoice)
           .WithMany(b => b.Payments);

            modelBuilder.Entity<ProductDetails>()
           .HasOne(p => p.SaleInvoice)
           .WithMany(b => b.ProductDetails);

            modelBuilder.Entity<Products>()
           .HasOne(p => p.ProductDetail)
           .WithMany(b => b.Products);

            modelBuilder.Entity<Products>()
           .HasOne(p => p.ProductionOrder)
           .WithMany(b => b.Products);

            modelBuilder.Entity<Products>()
           .HasOne(p => p.Employee)
           .WithMany(b => b.Products);

            modelBuilder.Entity<Products>()
           .HasOne(p => p.Category)
           .WithMany(b => b.Products);

            modelBuilder.Entity<ProductionOrders>()
           .HasOne(p => p.RawMaterial)
           .WithMany(b => b.ProductionOrders);

            modelBuilder.Entity<SuplierInvoices>()
           .HasOne(p => p.RawMaterial)
           .WithMany(b => b.SuplierInvoices);

            modelBuilder.Entity<SuplierInvoices>()
           .HasOne(p => p.Suplier)
           .WithMany(b => b.SuplierInvoices);

            modelBuilder.Entity<Supliers>()
           .HasOne(p => p.SuplierCity)
           .WithMany(b => b.Supliers);

            modelBuilder.Entity<SuplierCities>()
           .HasOne(p => p.SuplierRegion)
           .WithMany(b => b.SuplierCities);

            modelBuilder.Entity<SuplierRegions>()
           .HasOne(p => p.SuplierCountry)
           .WithMany(b => b.SuplierRegions);

            base.OnModelCreating(modelBuilder);
        }

    }
}

Я пробовал все, что говорит этот сайт, включая перезапуск VS:

enable-migrations -ProjectName Manufactura -Verbose

Enable-Migrations -ProjectName Manufactura -ContextTypeName Manufactura.Models.ApplicationDbContext

Enable-Migrations -ProjectName Manufactura -ContextTypeName Manufactura.Models.ApplicationDbContext -force

Install-Package EntityFramework -IncludePrerelease

UnInstall-Package EntityFramework 

Install-Package EntityFramework

Это приложение .Net Core 3.1 в VS 2019.

Если я раскомментирую System.Data.Entity, я получаю сообщение об ошибке: DbContext является неоднозначной ссылкой

Ничего не работает.

это мои настройки приложения

{
  "ConnectionStrings": {
    "ConnectionString": "Data Source=.;Initial catalog=confecciones;Integrated Security=true"
  },

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Usin f12 на DbContext, это приводит меня сюда:

namespace Microsoft.EntityFrameworkCore
ublic class DbContext : IDisposable, IAsyncDisposable, IInfrastructure<IServiceProvider>, IDbContextDependencies, IDbSetCache, IDbContextPoolable, IResettableService
    {
        //
        // Resumen:
        //     Initializes a new instance of the Microsoft.EntityFrameworkCore.DbContext class
        //     using the specified options. The Microsoft.EntityFrameworkCore.DbContext.OnConfiguring(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder)
        //     method will still be called to allow further configuration of the options.
        //
        // Parámetros:
        //   options:
        //     The options for this context.
        public DbContext([NotNullAttribute] DbContextOptions options);
        //
        // Resumen:
        //     Initializes a new instance of the Microsoft.EntityFrameworkCore.DbContext class.
        //     The Microsoft.EntityFrameworkCore.DbContext.OnConfiguring(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder)
        //     method will be called to configure the database (and other options) to be used
        //     for this context.
        protected DbContext();

Код запуска:

using System;
using System.Collections.Generic;
using System.Linq;
//using System.Data.Entity;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Manufactura.Models;
using Microsoft.Extensions.Hosting;

namespace Manufactura
{
    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.AddRazorPages();
                        
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
            services.AddControllers();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

Настройки приложения:

{


  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ConnectionString": "Data Source=DESKTOP-APHO8VE\\SQLEXPRESS;Initial catalog=confecciones;Integrated Security=true"
  }
}

person Hernandez400    schedule 23.06.2020    source источник
comment
Скорее всего, вы ссылаетесь на неправильный DbContext, наведите на него курсор и нажмите F12 для проверки.   -  person NotImplementedException    schedule 23.06.2020
comment
Меня приводит сюда: пространство имен Microsoft.EntityFrameworkCore   -  person Hernandez400    schedule 23.06.2020
comment
Попробуйте удалить обычный пакет Entity framework из ваших пакетов, не стесняйтесь, напишите мне ссылку на github, если вы все еще застряли после этого.   -  person NotImplementedException    schedule 23.06.2020
comment
Привет, я пробовал это несколько раз ... Я даже просто удалил VS и снова установил   -  person Hernandez400    schedule 23.06.2020
comment
Воспроизведите проблему в новом проекте, чтобы проверить, я не могу ее воспроизвести...   -  person NotImplementedException    schedule 23.06.2020
comment
В новом проекте ошибка: в сборке не найден тип контекста. Можете ли вы поделиться ссылкой на проект, который вы сделали, и в котором нет ошибки?   -  person Hernandez400    schedule 24.06.2020
comment
Давайте продолжим это обсуждение в чате.   -  person NotImplementedException    schedule 24.06.2020


Ответы (2)


Похоже, у вас есть EntityFrameworkCore и EntityFramework 6.x (или версия до .NET Core) в одном и том же решении: пространство имен System.Data.Entity предназначено для EF6 и т. д.

Если вы должны использовать две версии вместе, Microsoft рекомендует более четко указать ваши пространства имен:

https://docs.microsoft.com/en-us/ef/efcore-and-ef6/side-by-side

person LJH    schedule 24.06.2020
comment
Мне не нужно два... только один, какой мне использовать? Я пытаюсь создать программное обеспечение для небольшой компании - person Hernandez400; 25.06.2020
comment
Я бы использовал Entity Framework Core. Удалите EF6 и установите EF Core с его инструментами и т. д. Используйте uninstall-package Microsoft.EntityFramework для удаления более ранних версий и install-package Microsoft.EntityFrameworkCore для EF Core. - person LJH; 25.06.2020
comment
Microsoft.EntityFramework для удаления не найден в проекте, я установил другой. После enable-миграции появляется ошибка В сборке не найден тип контекста - person Hernandez400; 25.06.2020
comment
Я думал, что Enable-migrations не используется в EF Core — вы используете Add-Migration. Если у вас более одного проекта, убедитесь, что проект, в котором, возможно, установлен EF6, установлен в качестве запускаемого проекта, затем перейдите в консоль диспетчера пакетов и запустите uninstall-package Entityframework. Я неправильно указал Microsoft.Entityframework ранее. - person LJH; 25.06.2020
comment
Я сделал то, что вы сказали, появляется эта ошибка: ваш целевой проект «Мануфактура» не ссылается на EntityFramework. Этот пакет необходим для работы основных инструментов Entity Framework. Убедитесь, что ваш целевой проект правильный, установите пакет и повторите попытку. - person Hernandez400; 25.06.2020

После того, что сказал @LJH, я снова и снова использовал одно и то же имя для миграции, я изменил его и использовал слишком короткую версию add-migration, и теперь это работает

person Hernandez400    schedule 26.06.2020