我假设我遗漏了一些东西,但当我在项目中生成迁移时,它们总是显示空的Up和Down方法。即使是在一个全新的项目中。以下是我的步骤。
启动Visual Studio 2019。创建一个新的ASP.NET Web Application (.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; }
}
}现在,我返回到Package Manager控制台,创建另一个迁移。我尝试创建一个新的迁移。
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()
{
}
}
}我遗漏了什么?为什么它不想用我的新表生成一个迁移?
按照要求,这就是Visual Studio生成的IdentityModel.cs类中的ApplicationDbContext。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}发布于 2020-12-15 22:22:27
如果您的第一次迁移创建了users表,那么我假设它使用的是IdentityDbContext。然后,您不需要从DbContext继承SchoolContext,而需要从IdentityDbContext继承。
更新:根据问题的最新更新,很明显应用程序已经有一个数据库上下文,即ApplicationDbContext。因此,通常将所有DbSet<>保存在一个数据库上下文中就足够了。不需要创建新的上下文。
发布于 2020-12-16 20:14:18
缺少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; }
}注意,有两个dbcontext没有明确的用法,只使用ApplicationDBContext并删除另一个。
https://stackoverflow.com/questions/65307434
复制相似问题