Set foreignkey with migration. (Custom database ta...
# help-with-umbraco
e
I've created a custom table using this umbraco guide: https://docs.umbraco.com/umbraco-cms/extending/database The table now works. But I can't set a foreign key with the migration. Can someone help me with setting the StatusId as foreign key reference? The following code is the same but I've anonymize the tablenames etc.
Copy code
C#
protected override void Migrate()
{
    Logger.LogDebug("Running migration {MigrationStep}", "AddCarTable");

    if (TableExists("Cars") == false)
    {
        Create.Table<CarStatusSchema>().Do();
        Create.Table<CarSchema>().Do();
    }
    else
    {
        Logger.LogDebug("The database table {DbTable} already exists, skipping", "Cars");
    }
}

[TableName("Cars")]
[PrimaryKey("Id", AutoIncrement = true)]
[ExplicitColumns]
public class CarSchema
{
    [PrimaryKeyColumn(AutoIncrement = true, IdentitySeed = 1)]
    [Column("Id")]
    public int Id { get; set; }

    [Column("Model")]
    public required string Model { get; set; }

    [Column("CarStatusId")]
    public required int CarStatusId { get; set; }
}

[TableName("CarStatus")]
[PrimaryKey("Id", AutoIncrement = true)]
public class CarStatusSchema
{
    [PrimaryKeyColumn(AutoIncrement = true, IdentitySeed = 1)]
    [Column("Id")]
    public int Id { get; set; }

    [Column("Status")]
    public string Status { get; set; }
}
I've also tried to add this reference (code below) but it also didn't work. (I can try to recreate the error if it helps)
Copy code
C#
[References(typeof(CarStatusSchema))]
    [Column("Status")]
    public CarStatusSchema StatusReference { get; set; }
I think I've found the solution using:
Copy code
C#
[ForeignKey(typeof(CarStatusSchema), Name = "FK_Car_CarStatus", Column = "CarStatusId")]
I will let you people know if it works
It worked. Thanks for the people who tried to find a solution in the mean time.
9 Views