Data Annotations Table Attribute in EF Core

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

Table Name Convention

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

Consider the following model.

entity framework core table name convention

The above entity model creates the table with the name 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 namespace

Table Attribute

Table attribute overrides the default 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 Core will create a table with the name specified in this attribute.

Syntax

Table Name

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

entity framework core table attribute

Table Schema

The above example creates 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

entity framework core table attribute with schema

The dbo is now changed to Admin. Also note that EF Core creates the Schema if does not exists.

References

  1. Table Attribute

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top