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.
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 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(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; }
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
//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; }
The dbo is now changed to Admin. Also note that EF Core creates the Schema if does not exists.
