【问题标题】:EF not creating identity table when trying to create new databaseEF 在尝试创建新数据库时未创建身份表
【发布时间】:2019-05-01 10:48:18
【问题描述】:

我有 2 个模型类:

  1. Customer.cs 带有名称和 ID
  2. Movies.cs 带有名称和 ID

我尝试运行enable-migrations,但出现此错误:

在程序集 WebApplication2' 中找不到上下文类型。

然后我在网站上看到了一些答案,人们告诉我要开设DBContext 课程。我没有任何 DBContext 类,因为我刚刚创建了一个新的 MVC 项目。 因此,我尝试创建自己的 DbContext 类,如下所示:

{
    public class MyDBContext:DbContext
    { 
        public void MyDbContext()
        {
        }
    }
}

然后我能够运行enable-migrtaions 命令并使用 configuration.cs 创建迁移文件夹,如下所示:

internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.MyDBContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(WebApplication2.Models.MyDBContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.
        }
    }
}

现在,当我运行 add-migration Initialmodel 时,Up() 和 Down() 方法为空,并且没有身份表。 请帮忙!

【问题讨论】:

  • 急需帮助
  • 您不需要在上下文中添加 DbSet 吗?

标签: asp.net asp.net-mvc entity-framework ef-code-first entity-framework-migrations


【解决方案1】:

首先我建议您参考使用实体框架创建一个新的 MVC 项目。有很多教程,但这里是微软的,它准确且非常完整:

Get Started with Entity Framework 6 Code First using MVC 5

它还包括关于迁移的部分,但是在您拥有正在更改的数据库和模型之前,您不需要迁移。

我建议在我们准备好之前退出您的迁移。 Rick Strahl 有一篇很好的文章,介绍了如何将它们退出并恢复到一个干净的状态:

Resetting Entity Framework Migrations to a clean State

最后,您的 DbContext 类必须有一个 DbSet。 DbSet 类是一个实体集,可用于创建、读取、更新和删除操作。对于您的 DbContext 类,Entity Framework 不知道该做什么或映射。

将您的 DbContext 类更改为以下内容:

{
public class MyDBContext:DbContext
{ 
    public void MyDbContext()
    {
    }

    public virtual DbSet<Movie> Movies {get; set;}
    public virtual DbSet<Customer> Customers {get; set;}
}

这将允许您(例如在控制器中)执行类似的操作以将新客户添加到数据库:

var customer = new Customer { name = "John Smith" };
using(var context = new MyDbContext())
{
   context.Customers.Add(customer); // adds the customer to the DbSet in memory
   context.SaveChanges(); // commits the changes to the database
}

注意:我不建议在控制器中以这种方式创建 DbContext,在使用 EF6 和 MVC 5 的第一个链接中,有更好的方法。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 2015-11-07
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多