0

I start learn EF Fluent API.

I have 2 simple POCO classes.

public class Customer
{
    public int CustomerId{ get; set;}
    public string Name{ get; set;}
}

public class Project
{
    public int ProjectId { get; set; }
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public Customer Customer { get; set; }
}

context class

   public class MyCtx:DbContext
    {
        public DbSet<Project> Projects { get; set; }
        public DbSet<Customer> Authors { get; set; }

        public MyCtx(string  connString):base(connString)
        {}

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //PK
            modelBuilder.Entity<Project>()
                .HasKey(p => p.ProjectId)
                .Property(p => p.ProjectId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
                .HasColumnName("PROJECT_ID")
                .IsRequired();


            modelBuilder.Entity<Project>()
                .Property(c => c.Name)
                .HasColumnName("NAME")
                .IsRequired();

            //--------------------------------------------------------------------

            //PK
            modelBuilder.Entity<Customer>()
                .HasKey(c => c.CustomerId)
                .Property(c => c.CustomerId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
                .HasColumnName("CUSTOMER_ID")
                .IsRequired();

            modelBuilder.Entity<Customer>()
                .Property(c => c.Name)
                .HasColumnName("NAME")
                .IsRequired();

            base.OnModelCreating(modelBuilder);
        }
    }

I defined that CustomerId will be primary key in table customer and ProjectId will be primary key in project table.

I am little surprised with this behavarior. CustomerId in project table is automatically foreign key.

This behavior is based on naming convention? Or how it works?

1 Answers1

0

Yes, it is based on a naming convention, in this case specifically the NavigationPropertyNameForeignKeyDiscoveryConvention:

Convention to discover foreign key properties whose names are a combination of the dependent navigation property name (Customer in your case) and the principal type primary key property name(s) (CustomerId in your case).

Or it is the PrimaryKeyNameForeignKeyDiscoveryConvention:

Convention to discover foreign key properties whose names match the principal type primary key property name(s).

I am not sure which one.

If you don't like one of those conventions you can remove them with the model builder:

modelBuilder.Conventions
    .Remove<NavigationPropertyNameForeignKeyDiscoveryConvention>();
// etc.

A complete list of all conventions is here.

Slauma
  • 175,098
  • 59
  • 401
  • 420