Introduction

Hi everyone. Today I will share the default behavior of Entity Framework that assumes that the table name in the database is pluralized.

For example, in the Code First approach you made entity (class) named Student and expect the Student Table will be created. But the default table created in the Db will be Students. We will understand it with creating a sample application.

Creating Sample Application

Create a sample console application.



Figure 1: Create an Application

Then install the Nuget package Entityframework.



Figure 2: Install Nuget Package

Now add a connection string in the App.config file as in the following:

  1. <connectionStrings>
  2. <add name="ConnString" connectionString="server=****;database=MVCSample;uid=**;password=***;Connection Timeout=3" providerName="System.Data.SqlClient"/>
  3. </connectionStrings>
Then write the following code:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Data.Entity;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace SingularTableSample
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. using(StudentDBContext studentDBContext = new StudentDBContext())
  15. {
  16. Student student = new Student();
  17. student.StudentName = "Vivek";
  18. studentDBContext.Students.Add(student);
  19. studentDBContext.SaveChanges();
  20. Console.ReadKey();
  21. }
  22. }
  23. }
  24. public class Student
  25. {
  26. [Key]
  27. public int StudentId
  28. {
  29. get;
  30. set;
  31. }
  32. public string StudentName
  33. {
  34. get;
  35. set;
  36. }
  37. }
  38. public class StudentDBContext: DbContext
  39. {
  40. public StudentDBContext(): base("ConnString")
  41. {
  42. }
  43. public DbSet < Student > Students
  44. {
  45. get;
  46. set;
  47. }
  48. }
  49. }
When you run the following code you will see that the Default Students Table is created.



Figure 3: Solution Explorer

For solving this problem the Entity Framework provides a very good approach, Conventions, that allow you to specify how you want your database to be set up.

Simply add the following code to your DBContext class and add the following namespace:
  1. using System.Data.Entity.ModelConfiguration.Conventions;
  2. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  3. {
  4. modelBuilder.Conventions.Remove < PluralizingTableNameConvention > ();
  5. }
This code will remove the Pluralizing convention that is the default behavior for all model builders. You will then be able to create tables with singular names.



Figure 4: Output

Refer to this link:

Pluralizing Table Name Convention Class