如何修复MERGE语句与FOREIGN KEY约束冲突



我正在尝试获取一些表:

迁移是:

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_许可证_产品_产品Id";。冲突发生在数据库"中;"应用许可服务器";,表";dbo。产品";,列"Id"。

但是发生了什么?我能修好吗?

这意味着Products表中没有与您试图插入(合并(的条目的行Id匹配的行。

通过您的评论,您似乎发现了一个问题,导致您的产品表为空,但我想添加以下内容:

注意:在您的模型中,ProductId外键不可为null,因此如果您不设置它,它将默认为0,如果该Id不存在,您也会收到此错误。

这个特殊的问题使我想到了你的问题。

最新更新