Home > Software design >  Foreign Key with no Ids for column with same name as navigational property
Foreign Key with no Ids for column with same name as navigational property

Time:04-09

I have the following tables.

CREATE TABLE Thing
(
    Id INT PRIMARY KEY IDENTITY(1, 1),
    CreatedByUser INT NOT NULL
)
 
CREATE TABLE User
(
    Id INT PRIMARY KEY IDENTITY(1, 1)
)

I have the following EF entities, defined (intentionally) with a navigational property without an Id.

public class Thing
{
    public int Id { get; set; }
 
    public User CreatedByUser { get; set; }
}
 
public class User
{
    public int Id { get; set; }
}

I would like to know how to define the foreign key relationship when the underlying Id field on the table is the same name as the navigation property I would like include on the entity model. The following example fails to find a db column with the name CreatedByUser_Id.

modelBuilder.Entity<Thing>()
  .HasOne(x => x.CreatedByUser)
  .WithMany()
  .HasForeignKey("CreatedByUser_Id")
  .IsRequired();

Thanks

CodePudding user response:

Fixed it with the following.

modelBuilder.Entity<Thing>()
    .HasOne(x => x.CreatedByUser)
    .WithMany()
    .HasForeignKey("CreatedByUser_Id")
    .IsRequired();

modelBuilder.Entity<Thing>()
    .Property("CreatedByUser_Id")
    .HasColumnName("CreatedByUser");
  • Related