Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 897
Sellorio Avatar asked Sep 26 '17 23:09

Sellorio


1 Answers

This might also happen if you define your models two way binded but forget to use it in fluent:

public class Customer
{
    public Guid Id { get; set; }
    public List<Order> Orders {get; set;}
}

public class Order
{
    public Guid Id { get; set; }
    
    public Guid CustomerId { get; set; }
    public Guid Customer { get; set; }
}

// AppDbContext
builder.Entity<Order>()
     .HasOne(x => x.Customer) // <-- EDIT: Also use it like this, not .HasOne<Customer>()
     .WithMany() //WRONG -> should be .WithMany(x => x.Orders) OR modify the model to not define the collection at the customer entity
     .HasForeignKey(x => x.CustomerId)
     .OnDelete(DeleteBehavior.SetNull)
;
like image 182
Lars van den Bosch Avatar answered Sep 19 '22 01:09

Lars van den Bosch