Search code examples
c#entity-frameworkef-model-first

Entity Framework Core - Foreign Key 1 (extra foreign key column)


I just upgraded to Entity Framework Core 2 and now I'm getting issues with an extra column existing and having a unique key even though it's not in my model and it's not defined anywhere else.

The index:

migrationBuilder.CreateTable(
    name: "Vouchers",
    columns: table => new
    {
        Id = table.Column<int>(nullable: false)
            .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
        Code = table.Column<Guid>(nullable: false),
        IsClaimed = table.Column<bool>(nullable: false),
        LastModified = table.Column<DateTime>(nullable: false),
        NumberOfUnits = table.Column<int>(nullable: false),
        TransactionId = table.Column<int>(nullable: false),
        TransactionId1 = table.Column<int>(nullable: true) // why is this here?
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_Vouchers", x => x.Id);
        table.ForeignKey(
            name: "FK_Vouchers_Transactions_TransactionId1",
            column: x => x.TransactionId1,
            principalTable: "Transactions",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    });

TransactionId1 isn't in the model:

public class Voucher : IAutoLastModified
{
    public int Id { get; set; }
    public DateTime LastModified { get; set; }

    public int TransactionId { get; set; }
    public Transaction Transaction { get; set; }

    public int NumberOfUnits { get; set; }
    public Guid Code { get; set; }
    public bool IsClaimed { get; set; }
}

Am I defining the Foreign Key wrongly?

modelBuilder.Entity<Voucher>().HasOne(x => x.Transaction).WithOne(x => x.Voucher).IsRequired(false);

My app fails because TransactionId1 is always going to be null and has a unique constraint that I can't remove.

Why did EF create an extra column for this table?


Solution

  • Okay so I figured out what the issue was (keeping the question here for anyone who makes the same mistake I did).

    I marked the relationship as Optional but the column was an int instead of int? so EF decided to add it's own column behind the scenes.

    After fixing this I had to recreate the database - migration did not complete successfully due to existing data.