AspNetCore.All 2.0.5决定为迁移创建一个新表,其名称与已存在的表相同,而不是更改现有表。
Add-Migration
成功生成迁移,但在运行Update-Database
时会抛出错误,因为已经存在具有相同名称的表。
我可以在开发时删除表格或手动修复脚本,但从长远来看这对我没有帮助。我需要了解这里为将来的迁移所做的事情。
这是应用的初始迁移。 DB只有这一个表。
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace GameApplication.Migrations
{
public partial class first : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "UserProfiles",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_UserProfiles", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "UserProfiles");
}
}
}
然后在新的添加迁移后,它包括:
migrationBuilder.CreateTable(
name: "UserProfiles",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
City = table.Column<string>(nullable: true),
Country = table.Column<string>(nullable: true),
DisplayName = table.Column<string>(nullable: true),
FirstName = table.Column<string>(nullable: true),
Langauge = table.Column<float>(nullable: false),
LastName = table.Column<string>(nullable: true),
Latitude = table.Column<float>(nullable: false),
Longitude = table.Column<float>(nullable: false),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_UserProfiles", x => x.Id);
});
Name
已删除并替换为FirstName LastName
这一事实,这通常会显示数据丢失警告。会导致这种情况发生的原因是什么?看似相关的未回答的问题: Add-Migration not adding column to existing table in Entity Framework Core
答案 0 :(得分:0)
我在写这个问题时解决了这个问题,所以:
EF计算出如何根据ApplicationContextModelSnapshot.cs
创建新的迁移,并且此文件在我的情况下不正确。
这个快照文件对我来说是破碎的,因为我的20180313134743_first.Designer.cs
文件已经过修改和评论。这意味着EF无法正确创建快照,或者它不存在,使其在尝试进行新迁移时不知道当前的模型状态。
要解决此问题:
remove-migration
命令的新迁移。20180313134743_first.Designer.cs BuildTargetModel()
的内容复制到ApplicationContextModelSnapshot.cs BuildModel()
Update-Database
验证,然后Add-Migration
,这次它成功识别出需要更改现有表格。