I open this question because of this unanswered/duplicate question of mine:
Multiple identity columns specified for table exception
The answer to this question is here:
Cant remove identity attribute from PK
in short: "I have to Re-Create my sql table in the migration Up method"
I have a User has many SchoolclassCode relation:
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; }
}
That is my INIT migration
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");
}
}
That is my Second migration which is throwing the error: invalid column name 'User_Id' when I do '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()
{
//
}
}
What do I wrong, that the update-database
fails?