我有独立更新的项目(.Net Core 2.0)和数据库(SQL Server)。我想将迁移添加到项目中。我已经完成的工作是搭建当前数据库并填充我的modelBuilder以使其等同于我的表关系,然后创建第一个迁移。在此初始迁移脚本中,所有表都被删除并重新创建,我不想丢失我的数据。 例如,这是我的“地址”模型构建器的外观:
builder.ToTable("Addresses");
builder.HasKey(x => x.Id);
builder.Property(e => e.City).HasMaxLength(250);
builder.Property(e => e.Country).HasMaxLength(50);
builder.Property(e => e.Notes).HasColumnType("text");
builder.Property(e => e.Number).HasMaxLength(50);
builder.HasOne(a => a.User).WithMany(u => u.Addresses)
.HasForeignKey(a => a.UserId);
builder.HasIndex(e => e.UserId)
.HasName("fkIdx_72");
这是上下文快照中的外观:
b.Property<long>("Id").ValueGeneratedOnAdd();
b.Property<string>("City").HasMaxLength(250);
b.Property<string>("Country").HasMaxLength(50);
b.Property<string>("Notes").HasColumnType("text");
b.Property<string>("Number").HasMaxLength(50);
b.Property<long?>("UserId");
b.HasKey("Id");
b.HasIndex("UserId").HasName("fkIdx_72");
b.ToTable("Addresses");
这是第一个迁移脚本。上法:
migrationBuilder.CreateTable(
name: "Addresses",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
City = table.Column<string>(maxLength: 250, nullable: true),
Country = table.Column<string>(maxLength: 50, nullable: true),
Notes = table.Column<string>(type: "text", nullable: true),
Number = table.Column<string>(maxLength: 50, nullable: true),
UserId = table.Column<long>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Addresses", x => x.Id);
table.ForeignKey(
name: "FK_Addresses_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
Down方法:
migrationBuilder.DropTable(
name: "Addresses");
为什么必须重新创建所有表?我想数据库中缺少什么... 有帮助吗?