-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Closed
Closed
Copy link
Milestone
Description
Steps to reproduce
- Generate a migration for the following model and create the database for SQL server via
Update-Database
command
public class Post
{
public int ID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
public class Tag
{
public string TagId { get; set; }
}
- Change the
PostId
column toID
- Now try to implement Many-To-Many as described here.
- Now generate the migration
migrationBuilder.DropPrimaryKey(
name: "PK_Posts",
table: "Posts");
migrationBuilder.DropColumn(
name: "PostId",
table: "Posts");
migrationBuilder.CreateTable(
name: "PostTag",
columns: table => new
{
PostId = table.Column<int>(nullable: false),
TagId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PostTag", x => new { x.PostId, x.TagId });
table.ForeignKey(
name: "FK_PostTag_Posts_PostId",
column: x => x.PostId,
principalTable: "Posts",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_PostTag_Tags_TagId",
column: x => x.TagId,
principalTable: "Tags",
principalColumn: "TagId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.AddColumn<int>(
name: "ID",
table: "Posts",
nullable: false,
defaultValue: 0)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
migrationBuilder.AddPrimaryKey(
name: "PK_Posts",
table: "Posts",
column: "ID");
migrationBuilder.CreateIndex(
name: "IX_PostTag_PostId",
table: "PostTag",
column: "PostId");
migrationBuilder.CreateIndex(
name: "IX_PostTag_TagId",
table: "PostTag",
column: "TagId");
The issue
- Run
Update-Database
and you will get the following error
Foreign key 'FK_PostTag_Posts_PostId' references invalid column 'ID' in referenced table 'Posts'.
Could not create constraint or index. See previous errors.
If you move the AddColumn
and AddPrimaryKey
calls before creating the join table, the error will move away.
You may get another error for issue #5660 which can be resolved by removing defaultValue
optional parameter.
Further technical details
EF Core version: 1.0
Operating system: Windows 10 x64
Visual Studio version: 2015 Update 3