Share via


CodeFirst EF 4.1 : Changing Database Table and Column name

At times we need to control the Table and Column name of our generated database or have different Entity/Property name of code than actual database in EF 4.1 Code First. There are two ways we can do it.

Using Annotations

 using System.ComponentModel.DataAnnotations;

    //Changing database Table name to Employee
    [Table("Employee")]
    public class Emp
    {
        //Changing database column name to EmpId
        [Column("EmpId")]
        public int Id { get; set; }
        public string Name { get; set; }
    }

Using FluentAPI

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //Changing Database Column name to EmployeeId
    modelBuilder.Entity<Emp>()
        .Property(p => p.Id)
        .HasColumnName("EmployeeId");

    //Changing Database table name to EmployeeData
    modelBuilder.Entity<Emp>()
        .ToTable("EmployeeData");
}
 Note: If you have both Annotation and FluentAPI available, the FluentAPI will win.

Namoskar!!!

Comments

  • Anonymous
    May 16, 2011
    its really very nice & useful
  • Anonymous
    May 25, 2015
    I implemented it. But i'm not able to see the changed name reflected in the database. Are there any other steps we need to perform to get it reflected in database as well.