CodeFirst EF 4.1 : Changing Database Table and Column name

CodeFirst EF 4.1 : Changing Database Table and Column name

  • Comments 1

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!!!

Leave a Comment
  • Please add 1 and 1 and type the answer here:
  • Post
  • its really very nice & useful

Page 1 of 1 (1 items)