[英]C# cannot update database with Entity Framework
我有一個問題,不幸的是我無法修復它,也找不到合適的解決方案。 有誰知道問題出在哪里? 我正在嘗試使用新的 TravelCountry 更新我的 Tours object。
遷移代碼:
migrationBuilder.DropColumn(
name: "TravelCountry",
table: "Tours");
migrationBuilder.AddColumn<int>(
name: "TravelCountryId",
table: "Tours",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "TravelCountries",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_TravelCountries", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_Tours_TravelCountryId",
table: "Tours",
column: "TravelCountryId");
migrationBuilder.AddForeignKey(
name: "FK_Tours_TravelCountries_TravelCountryId",
table: "Tours",
column: "TravelCountryId",
principalTable: "TravelCountries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
它在“migraitonBuilder.AddForeignKey”處失敗並出現錯誤:
無法添加或更新子行:外鍵約束失敗(
gam_db
.#sql-1e1c_fe
,CONSTRAINTFK_Tours_TravelCountries_TravelCountryId
FOREIGN KEY (TravelCountryId
) REFERENCEStravelcountries
(Id
) ON DELETE CASCADE)
這是我的旅行 object:
public class Tour
{
[Key]
public int Id { get; set; }
[Required]
public TravelCountry? TravelCountry { get; set; }
}
這是我的 TravelCountry object:
public class TravelCountry
{
[Key]
public int Id { get; set; }
[Required]
public string? Name { get; set; }
}
您需要在您的游覽 model 中添加一個外鍵,以便在此 twp 表之間創建關系,例如:
public int? CategoryId { get; set; }
[ForeignKey("TravelCountryId")]
還要確保你擁有所有的 nugets 並且不要忘記在添加遷移后控制台 package manger 中的命令 update-database
只有一個問題:為什么實體列是 [required] 而代碼中的變量可以是 null? 也許刪除聲明中的問號,因為 [required] 意味着這個值不能是 null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.