Data Annotations Table Attribute EF 6 & EF Core

We use the Table Attribute or Table Name Attribute to specify the table name and schema to the Entity Framework or Entity Framework Core.

Table Name Convention

The Table Name conventions works differently in Entity Framework & Entity Framework Core

Entity Framework Core

The Default EF Core conventions use the DbSet Property name as the table name or name of the class if DbSet property is not available

Entity Framework

The Default entity framework code first convention uses the pluralized form of an entity class name to create the database table.

Consider the following model.

Table Name Convention in Entity Framework and Entity Framework Core
Table Name Code First Convention

The above entity model creates the table with the name customers in Entity Framework and Customer in EF Core as shown in the image above. You can override this behavior using the Table attribute. This attribute resides in System.ComponentModel .DataAnnotations .Schema

Table Attribute

Table attribute overrides the default entity framework code first convention or EF Core Conventions, which creates the table with the name same as the Class Name. We apply the attribute to the class and not on the Property.  The EF will create a table with the name specified in this attribute.

Syntax

Best Entity Framework Core Books

Best Entity Framework Books

Table Name

In the following example, we have updated our domain model Customer and applied the table attribute CustomerMaster

TableName Attribute

Table Schema

The above example created the table CustomerMaster under the schema dbo. You can also specify a table schema using the Schema attribute as shown below. The example below creates the CustomerMaster table with the schema “Admin”

Table Attribute with Schema
Table Attribute with Schema

The dbo is now changed to Admin

References

  1. Data Annotations in Entity Framework & EF Core
  2. Entity Framework Conventions
  3. Entity Framework Core Conventions
  4. Table Attribute

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top