我打开这个问题是因为我的这个未答复/重复的问题:
Multiple identity columns specified for table exception
这个问题的答案在这里:
Cant remove identity attribute from PK
简而言之:" 我必须在迁移Up方法中重新创建我的sql表 "
我有一个用户有很多SchoolclassCode关系:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<SchoolclassCode> SchoolclassCodes { get; set; }
}
public class SchoolclassCode
{
public int Id { get; set; }
public string Schoolclass { get; set; }
public string Type { get; set; }
public User User { get; set; }
public int UserId { get; set; }
}
这是我的 INIT迁移
public partial class Init: DbMigration
{
public override void Up()
{
CreateTable(
"dbo.SchoolclassCodes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Schoolclass = c.String(),
Type = c.String(),
User_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.User_Id)
.Index(t => t.User_Id);
CreateTable(
"dbo.Users",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropForeignKey("dbo.SchoolclassCodes", "User_Id", "dbo.Users");
DropIndex("dbo.SchoolclassCodes", new[] { "User_Id" });
DropTable("dbo.Users");
DropTable("dbo.SchoolclassCodes");
}
}
这是我的第二次迁移,它引发了错误:无效的列名称&#39; User_Id&#39;当我做'Update-database'
public partial class ReCreateTable : DbMigration
{
public override void Up()
{
// backup schoolclassCodes table
DropTable("SchoolclassCodes");
CreateTable("SchoolclassCodes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Schoolclass = c.String(maxLength: 3), // 12a,7b
Type = c.String(),
UserId = c.Int(nullable: false,identity:false)
})
.PrimaryKey(t => t.Id)
.ForeignKey("Users", t => t.UserId, cascadeDelete: true)
.Index(s => s.Schoolclass, unique: true);
// Delete Table Users
Sql("Delete from Users");
// Re-Insert data
SqlFile("./Migrations/data.sql");
}
public override void Down()
{
//
}
}
我错了,update-database
失败了吗?
答案 0 :(得分:0)
如果要删除在第一次迁移中创建的所有内容,请按照Down()代码中的描述删除它们:
// backup schoolclassCodes table
DropForeignKey("dbo.SchoolclassCodes", "User_Id", "dbo.Users");
DropIndex("dbo.SchoolclassCodes", new[] { "User_Id" });
// DropTable("dbo.Users");
DropTable("dbo.SchoolclassCodes");
观察,似乎您需要将旧数据与迁移相结合。我会将两者分开。
首先,保存旧数据。如果音量较低,请考虑将其添加到Seed()方法中。否则,在SQL中重命名表,并在迁移添加更正的表后使用SQL重新填充它们。
迁移旨在让您从模型中构建数据库,因此我将删除这两个迁移并添加一个代表您当前模型的新迁移。