Amadou Daffe
Amadou Daffe

Reputation: 21

Entity Framework Code first using Fluent Mapping for different Column Key names for different tables and entities

Using code first with existing database. I have 2 tables with different primary and foreign key name. For example

public class Person
{
    public int PersonID {get; set;}
    public virtual Sale {get; set;}
    public ICollection<Order> Orders {get; set;}
   //props
}

public class Sale
{
    public int saleId {get; set;}
    public int PersID {get; set;}
    //props
}
public class Oder
{
   public int OrderId {get; set;}
   public int pID {get set;}
}

Assuming that the PK in table Person is PersonID, in Order is pID and the FK in Sale PersID (so the naming convention for IDs is different from table to table)

How do I map the entities using fluent while taking into consideration the different column ID names?

Upvotes: 2

Views: 1146

Answers (1)

Matt Hamilton
Matt Hamilton

Reputation: 204219

So EF will already be picking up PersonID as the primary key of your Persons (People?) table. Of course, you can always write:

modelBuilder.Entity<Person>().HasKey(p => p.PersonID);

Then you want to describe the relationship between Person and Sale. I'm going to assume your Sale class has a navigation property of type Person called "Person":

modelBuilder.Entity<Sale>().HasRequired(s => s.Person)
                           .WithMany()
                           .HasForeignKey(s => s.PersID);

The "HasForeignKey" method lets you specify the property on your class that defines the foreign key value.

Don't forget that it's also ok to omit foreign key properties altogether. You might want to ditch the PersID property and tell EF that the database column is called "PersID" like this:

modelBuilder.Entity<Sale>().HasRequired(s => s.Person)
                           .WithMany()
                           .Map(m => m.MapKey("PersID"));

Upvotes: 1

Related Questions