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?