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.

public class Customer
{
   public int CustomerID { get; set; }
   public string Name { get; set; }
}

//Add this in Context class
public DbSet<Customer> Customer { get; set; }

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

Table(string name, Properties:[Schema = string])

Where
Name:  Sets the name of the table the class is mapped to. 
Schema: Sets the schema of the table the class is mapped to.

Table Name

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

//Import required
using System.ComponentModel.DataAnnotations.Schema;

[Table("CustomerMaster")]
public class Customer
{
  public int CustomerID { get; set; }
  public string Name { get; set; }
}

//Add this in Context class
public DbSet<Customer> Customer { get; set; }
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”

//Import required
using System.ComponentModel.DataAnnotations.Schema;

[Table("CustomerMaster", Schema = "Admin")]
public class Customer
{
  public int CustomerID { get; set; }
  public string Name { get; set; }
} 

//Add this in Context class
public DbSet<Customer> Customer { get; set; }
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. Required fields are marked *

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

Scroll to Top