Thursday 9 July 2015

Avoiding pluralization in the Data Context class

When we are designing the Data Access as code first, the Data Context is looking for pluralized tables in the DB.

Eg :

public DbSet<Student> StudentSet{ get; set; } 

This is looking for the table Students in the database.

If we want to use the same table name, we need to remove the PluralizingTableNameConvention attribute from the lmodelBuilder. The full example is as follows

 public class SchoolContext : DbContext
    {
        public SchoolContext ()
            : base("name=SchoolCon")
        {
            Database.SetInitializer<SchoolContext>(null);
        }

        public DbSet<Student> StudentSet { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<Student>().HasKey<int<(e => e.StudentId);
        }
    }


No comments:

Post a Comment