Home > Enterprise >  C# cannot update database with Entity Framework
C# cannot update database with Entity Framework

Time:12-07

I have a problem, unfortunately I can not fix it and can not find a proper solution to this. Does anyone know what the problem is? I am trying to update my Tours object with a new TravelCountry.

Migration Code:

 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);

It fails at "migraitonBuilder.AddForeignKey" with the error:

Cannot add or update a child row: a foreign key constraint fails (gam_db.#sql-1e1c_fe, CONSTRAINT FK_Tours_TravelCountries_TravelCountryId FOREIGN KEY (TravelCountryId) REFERENCES travelcountries (Id) ON DELETE CASCADE)

Heres my Tour object:

 public class Tour
{
    [Key]
    public int Id { get; set; }

    [Required]
    public TravelCountry? TravelCountry { get; set; }
}

And here is my TravelCountry object:

 public class TravelCountry
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string? Name { get; set; }
}

CodePudding user response:

you need to add a foreign key to your tour model in order to create a relationship between this twp tables for example:

public int? CategoryId { get; set; }
    [ForeignKey("TravelCountryId")]

also make sure you have all the nugets and dont forget the command update-database in console package manger after adding the migrations

CodePudding user response:

Just one question: why is the entity column [required] whilst the variable in the code can be null? Maybe delete the question marks in the declarations because [required] means that this value cannot be null

  • Related