【问题标题】:ASP.NET MVC Code-First Building Empty MigrationsASP.NET MVC 代码优先构建空迁移
【发布时间】:2021-03-26 04:18:41
【问题描述】:

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

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

接下来我启用迁移。

Enable-Migrations

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

Add-Migration First

第一次迁移成功添加了各个用户帐户的所有身份信息。一切都很好。

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

Update-Database

现在,我在 Models 文件夹中添加一个名为 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

但这一次,班级是空的。它不会创建我的新表。

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

        }
        
        public override void Down()
        {
            
        }
    }
}

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

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

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

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

}

【问题讨论】:

标签: c# .net asp.net-mvc asp.net-mvc-4 ef-code-first


【解决方案1】:

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

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

【讨论】:

  • 我尝试继承IdentityDbContext&lt;ApplicationUser&gt;,但没有成功。但我确实发现将这个public DbSet&lt;Student&gt; Students { get; set; } 直接添加到 IdentityModel.cs 中的 ApplicationDbContext 方法是有效的。然后迁移正确生成。不知道我是否明白为什么。
  • 你能把你的“ApplicationDbContext”课程贴在这里吗?
  • 我会把它添加到我的原始帖子中
【解决方案2】:

您缺少 dbset 属性。

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

如果您已经有待迁移的迁移,则为代码编写 -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 个 dbcontexts 使用不明确,仅使用 ApplicationDBContext 并删除另一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多