Thursday, 26 February 2026

Fixing Duplicate Foreign Key Issue in EF / EF Core

Fixing Duplicate Foreign Key Issue in EF / EF Core

Sometimes when defining relationships in Entity Framework Core, the framework creates the same foreign key column twice — for example MasterId and a shadow Master_Id column — because the relationship is ambiguous.

In this article, I’ll show why this happens and how to explicitly configure navigation properties so only one foreign key is created.

Problem Code Example

public class Master
{
    public int Id { get; set; }
    public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public int MasterId { get; set; }
    public Master Master { get; set; }
}

If EF Core isn’t sure which property is the foreign key, it may generate two columns in the database. To fix that, we need to define the relationship explicitly.

Solution 1 — Using Data Annotation

using System.ComponentModel.DataAnnotations.Schema;

public class Child
{
    public int Id { get; set; }
    public int MasterId { get; set; }

    [ForeignKey(nameof(MasterId))]
    public Master Master { get; set; }
}

This tells EF Core that the MasterId field is definitely the foreign key for the Master navigation property.

Solution 2 — Using Fluent API

In your DbContext class:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Child>()
        .HasOne(c => c.Master)
        .WithMany(m => m.Childs)
        .HasForeignKey(c => c.MasterId);
}

This forces EF Core to map the relationship exactly the way you intend.

Key Takeaways

  • Avoid relying solely on conventions when you have both FK fields and navigation properties.
  • Use [ForeignKey] or Fluent API to map relationships explicitly.

If you follow these steps, EF Core will generate only one foreign key column in the database.

Posted by Arulkumar Sivaraj

No comments:

Post a Comment