ASP.NET MVC 代码优先构建空迁移

ASP.NET MVC Code-First Building Empty Migrations

我假设我遗漏了一些东西,但是当我在项目中生成迁移时,它们一直显示空的 Up 和 Down 方法。即使是在一个全新的项目中。这是我的步骤。

启动 Visual Studio 2019。创建一个新的 ASP.NET Web 应用程序(.net 框架)C# 项目 (4.7.2)。选择 MVC 和身份验证 select 个人用户帐户。点击创建创建项目。

接下来我启用迁移。

Enable-Migrations

接下来我添加我的第一个迁移。

Add-Migration First

首次迁移已成功添加,其中包含个人用户帐户的所有身份信息。一切都很好。

我更新数据库以应用迁移。一切都还好。

Update-Database

现在,我将一个新的 class 添加到名为 SchoolContext 的模型文件夹中。

using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace WebApplication6.Models
{
    public class SchoolContext : DbContext
    {
        public DbSet<Student> Students { get; set; }    
        public SchoolContext() : base("DefaultConnection") { }
    }

    public class Student
    {
        [Key]
        public int StudentID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }

    }
}

我现在返回包管理器控制台创建另一个迁移。我尝试创建一个新的迁移。

Add-Migration Second

但这一次,class 是空的。它不会创建我的新 table.

namespace WebApplication6.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class Second : DbMigration
    {
        public override void Up()
        {

        }
        
        public override void Down()
        {
            
        }
    }
}

我错过了什么?为什么它不想用我的新 table 生成迁移?

根据要求,这就是我的 IdentityModel.cs class 中由 Visual Studio 生成的 ApplicationDbContext 的样子。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

}

如果您的第一次迁移创建了用户表,那么我假设它使用了 IdentityDbContext。然后,您需要继承您的 SchoolContext,而不是从 DbContext,而是从 IdentityDbContext.

更新:根据问题的最新更新,很明显应用程序已经有一个数据库上下文,即ApplicationDbContext。所以通常将所有 DbSet<> 保存在一个数据库上下文中就足够了。无需创建新上下文。

您缺少数据库集 属性。

将其作为以下示例,以便迁移可以检测到新的class/table。 添加dbset属性后,添加新的migration可以看到新写的class

如果您已经有待处理的迁移,请为代码写入 -force 以查看新更改并更新迁移

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
    public ApplicationDbContext() : base("DefaultConnection") {
     }

    public static ApplicationDbContext Create()
     {
        return new ApplicationDbContext();
     }

    public virtual DbSet<Student> Students { get; set; }
   }

请注意,有 2 个 dbcontext 没有明确的用途,仅使用 ApplicationDBContext 并删除另一个。