ASP.NET MVC:错误 CS0311:类型 'XYZ' 不能用作泛型方法中的参数 'TContext'

ASP.NET MVC: Error CS0311: The Type 'XYZ' can't be used as a parameter 'TContext' in generic method

我正在使用 .net MVC。我的项目中 enabled migrations 已成功完成。但是我在 Migrations>Configrations.cs 中遇到错误。错误如下。

CS0311:类型 'BabyStore.DAL.StoreContext' 不能用作泛型类型或方法 'DbMigrationsConfiguration' 中的类型参数 'TContext'。没有从 'BabyStore.DAL.StoreContext' 到 'System.Data.Entity.DbContext'

的隐式引用转换

我已经启用迁移如下

PM>Enable-Migrations -ContextTypeName BabyStore.DAL.StoreContext

BabyStore.DAL.ContextStore.cs的代码是

    namespace BabyStore.DAL
{
    public class StoreContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<Category> Categories { get; set; }

    }
}

最后我出错的代码如下 BabyStore.Migrations.Configurations.cs

   namespace BabyStore.Migrations
{

using System.Data.Entity.Migrations;

    internal sealed class Configuration : DbMigrationsConfiguration<BabyStore.DAL.StoreContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(BabyStore.DAL.StoreContext _context)
        {
            var categories = new List<Category>
            {
            new Category { Name = "Clothes"},
            new Category { Name = "Play and Toy" }
            };
            categories.ForEach(c => _context.Categories.AddOrUpdate(p => p.Name, c));
            _context.SaveChanges();

            var products = new List<Product>
            {
            new Product {Name="Sleep Suit", Desccription="For Sleeping wear",Price=100,CategoryID=categories.Single(c=>c.Name=="Clouths").ID },
            new Product {Name="Vest", Desccription="For Sleeping wear",Price=200,CategoryID=categories.Single(c=>c.Name=="Clouths").ID}
             };
            products.ForEach(c => _context.Products.AddOrUpdate(p => p.Name, c));
            _context.SaveChange();

        }
    }
}

我在 内部密封 class 配置中遇到错误:DbMigrationsConfiguration

强制迁移怎么样?使用 -force 参数

PM>Enable-Migrations -ContextTypeName BabyStore.DAL.StoreContext -force

我认为有拼写错误。换衣服换衣服

new Product {Name="Sleep Suit", Desccription="For Sleeping wear",Price=100,CategoryID=categories.Single(c=>c.Name=="Cloths").ID },
new Product {Name="Vest", Description="For Sleeping wear",Price=200,CategoryID=categories.Single(c=>c.Name=="Cloths").ID}

我已经检查过你所引用的书,它是 ASP.net MVC with Entity Framework CSS 并且它是 repo https://github.com/Apress/asp.net-mvc-w-entity-framework-css。如果你检查包,它使用 "EntityFramework.6.1.3" 这与 .net core 不同。

您可以在 visual studio 中重新创建您的项目,这次是 select ASP.NET Web 应用程序 (.NET Framework)。问题是由于不同的 entity framework 包。请参考此 以在 asp.net 内核上设置自动迁移。

查看 class signature 表明通用参数 TContext 被限制为类型 DbContext

public class DbMigrationsConfiguration<TContext> : System.Data.Entity.Migrations.DbMigrationsConfiguration where TContext : DbContext

修改您的 StoreContext 以继承 System.Data.Entity.DbContext

public class StoreContext : DbContext