Wednesday, December 2, 2015

Configure Code First migrations to use Singular Table Names

If you are using Code First Migration with Entity Framework you will probably have noticed that the table names it generates are all plural. Personally, I dislike this because all the contstraints including foreign keys are very confusing to read when they are plurarlized. Before you do an update-database for the first time be sure to override a method (OnModelCreating()) on your class (typicaly ApplicaionDbContext) that inherits from IdentityDbContext. The default class is called ApplicationDbContext.



public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        public DbSet People{ get; set; }
      

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // make the table names singular instead of plural
            //when code-first generates the table names

            modelBuilder.Conventions.Remove();
            base.OnModelCreating(modelBuilder);
        }


    }


No comments: