Search code examples
c#entity-framework-coreasp.net-core-5.0

Entity Framework generates new column rather than using the mentioned foreign key


I'm using code-first approach to create database tables. When the migration happens it creates a new column name ReceiverUserInfoId in the database table Complaints. I have defined the foreign key relation as:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");
    
    modelBuilder.Entity<Complaint>()
        .HasOne(x => x.ReceiverUserInfo)
        .WithMany()
        .HasForeignKey("ReceivingOfficer")
        .OnDelete(DeleteBehavior.Cascade)
        .IsRequired();
}

Model for Complaint. ReceivingOfficer column should linked to column name Id in database table AspNetUsers

public class Complaint
{
    [Key]
    public int? ComplaintID { get; set; }
    ...
    public string ReceivingOfficer { get; set; }
    ...
    public virtual User ReceiverUserInfo { get; set; }
}

Here's the User model class:

public class User : IdentityUser
{
    public string FullName { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
}

Here's how the relationship looks like via SSMS:

enter image description here


Solution

  • I have tried replicating your issue using the information you have provided and it works for me. Please double check the following points:

    1. Are you sure that migration is being executed?
    2. Are you importing modelBuilder from another file? If yes, are you sure that the file is being included in OnModelCreating