Data Annotations Table Attribute Entity Framework

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

Table Name Convention

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.

The above entity model creates the table with the name customers in Entity Framework as shown in the image above. Note that the table name is pluralized. You can override this behavior using the Table attribute. This attribute resides in System.ComponentModel.DataAnnotations.Schema

TableName default Convention in Entity Framework

Table Attribute

Table attribute overrides the default entity framework code first convention, 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 Entity Framework

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”

Data Annotation Table Attribute with Schema in Entity Framework

The dbo is now changed to Admin. If the schema does not exists, then EF will create one.

References

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