【发布时间】:2022-11-10 12:39:05
【问题描述】:
我正在尝试获取一些表格:
迁移是:
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
Version = table.Column<string>(type: "nvarchar(max)", nullable: true),
ReleaseDate = table.Column<DateTime>(type: "datetime2", nullable: false),
IsReleased = table.Column<bool>(type: "bit", nullable: false),
IsActive = table.Column<bool>(type: "bit", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
Modified = table.Column<DateTime>(type: "datetime2", nullable: false),
RowVersion = table.Column<byte[]>(type: "rowversion", rowVersion: true, nullable: true),
TestText = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Licenses",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Licensenumber = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false),
ProductId = table.Column<int>(type: "int", nullable: false),
UserId = table.Column<int>(type: "int", nullable: false),
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
Modified = table.Column<DateTime>(type: "datetime2", nullable: false),
RowVersion = table.Column<byte[]>(type: "rowversion", rowVersion: true, nullable: true),
TestText = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Licenses", x => x.Id);
table.ForeignKey(
name: "FK_Licenses_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Licenses_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
现在我正在创建数据库:MERGE 语句与 FOREIGN KEY 约束“FK_Licenses_Products_ProductId”冲突。冲突发生在数据库“app-licenseserver”、表“dbo.Products”、列“Id”中。
但是发生了什么?我可以修复它吗?
【问题讨论】:
-
您在外部表中创建条目,或者在不禁用外键的情况下无法插入。如果你不知道什么是外键,你需要找出来。
-
@Kendle 感谢您的回答。我知道,外键是什么。但如果“FK_Licenses_Products_ProductId”是唯一的,那应该不是问题。还是我错过了什么?
-
之前 product.Id 中是否存在许可证的 productID 值?
-
异常是 migrationBuilder 代码抛出的吗?我希望在某处你有类似于
context.Set<License>().Add(new License());后跟context.SaveChanges();的东西,并且外键被违反,因为ProductId是0。 -
@AlwaysLearning 确实你是对的。数据播种被破坏,并且在 SaveChanges 时间,Product 表为空。现在它起作用了。谢谢。
标签: sql-server entity-framework-core