Search code examples
entity-framework-coreentity-framework-migrationscode-first

How to change foreign key suffix in Entity Framework Core?


In EF Core with a code-first approach, by default column referencing another entity has an Id suffix - for example PersonId.

Is it possible - and if so, how? - to change it to _id, so to person_id?


Solution

  • Create the foreign key explicitly under the name you want - in your case Parent_Id. Keep a navigation property and foreign key property.

        public int Parent_ID { get; set; }
        public virtual Parent Parent { get; set; }
    

    Map the foreign key relations using .HasForeignKey(). Something similar as below

        builder.HasOne(d => d.Prop)
            .WithMany(p => p.NavigationProp)
            .HasForeignKey(d => d.ForeignKeyProp)
            .OnDelete(DeleteBehavior.ClientSetNull)
            .HasConstraintName("FK_ConstraintName");
    
    

    If you prefer data annotation, you could also use

        [Column("Parent_ID")]
        public int ParentID { get; set; }