Tuesday, July 5, 2011

Code: EF Code First Column Name Mapping

When using Entity Framework Code First there are a couple of ways to map your classes to your database, below is a code snippet of what made the most sense to me.  It maps property names to column names, denotes the table name to use for the class, and specifies the primary key.  There are also a handful of different properties on this class, but because they have the same name as the column in the database they don't need to be explicitly set.

public class LocateDB : DbContext
    public LocateDB()
        : base("LocateDB")
    public DbSet<LocateAccount> LocateAccounts { getset; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        var entity = modelBuilder.Entity<LocateAccount>();
        entity.Property(x => x.PR_Fax).HasColumnName("PR_Fax#");
        entity.Property(x => x.PRATT_Fax).HasColumnName("PRATT_Fax#");
        entity.HasKey(x => x.LocateId);