Entity framework – Code first – Disable pluralization of your tables

I have the following model :-

namespace AddressBook.Models
{
public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
}
}

The table name in the database :- “Contact”.

DbContext
public class AddressBookDb : DbContext
{
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating( DbModelBuilder dbModelBuilder)
{
dbModelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

Using any of the views, gives the following error :-

Invalid object name dbo.Contacts.

Obviously, entity framework is trying to pluralize the table name and expecting the table with the pluralized named database. This would be a problem for existing tables which you obviously don’t want to rename.

Just override the OnModelCreating method and remove that “PluralizingTableNameConvention” convention.

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

Note :- Need to add the namespace :- System.Data.Entity.ModelConfiguration.Conventions;

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Random Thoughts

The World as I see it

Simple Programmer

Making The Complex Simple

Ionic Solutions

Random thoughts on software construction, design patterns and optimization.

Long (Way) Off

A tragic's view from the cricket hinterlands

%d bloggers like this: