Entity Framework Core Conventions

EF Core Conventions or the default rules that you follow while creating the entity model. The EF Core uses these to infer and to configure the Database.   It uses the information available in the POCO Classes to determine and infer the schema of the database that these classes are mapped to. For example, the table name, Column Name, Data Type, Primary keys are inferred from the  Class name, property name & Property type by convention to build the database.

Conventions in EF Core

The EF Core makes certain assumptions based on how your code for domain model is written before creating the tables in the database. These are called Entity Framework core conventions or Entity Framework core naming conventions.

Preparing the Example Project

Create a new console app. We covered this in the tutorial EF Core example application. Name the project as EFCoreConventions. Install the following packages via NuGet Package Manager.

Create Models folder

Under the Models folder create the Context class EFContext.cs as shown here

Under the Models folder create the models.cs, which is going to hold our domain models

Now, we are ready

Type Discovery

Every entity model must declare a DbSet property in the DbContext. EF Core builds the database by inspecting the DbSet Property using the reflection. It then creates tables for these types. It also includes the referenced types, which do not expose DbSet Property. Inherited types are also created if the base class exposed the DbSet Property

Open the Models.cs and add the customer class as shown below

Open the Context class and add the DbSet Property for the customer Model

Now, open the Package Console Manager and run the command

Open the database and you should be able to see the following

EF Core Type Discovery Conventions

The Customer table is created. Note that the table name is taken from the  DbSet Property as Customers

Next, we will add another model CustmerAddress

Do not add DbSet property for the CustomerAddress table.

You can remove the migration by running the following commands in PMC.

Then, apply the migration again.

Check the Database. You will see the CustomerAddress table is created. This is because it is referenced by the Customer Table.

EF Core Table Name Conventions

Entity Class Convention

As seen in the above example, the entity classes are mapped to the database. For Entity Classes  to be mapped to the database, they need to follow few conventions

  • The class must be declared as public
  • Static classes are not allowed. The EF must be able to create an instance of the class
  • The Class should not have any constructor with a parameter. The parameterless constructor is allowed

Database Schema Name Convention

The EF Core creates the database using the schema is dbo.

Table Name Convention

EF Core creates the tables using the Dbset property of the entity class names. In the above example, the table name for customer class is customers as it is defined as customers in DbSet

If The DbSet property is not defined, then the class name is taken as default as in the case of customerAddress table

Remember, the old entity framework code first conventions used to pluralize the table names by default. This is dropped in EF Core.

Column Name

Table Column names are named after the property name. The property must have a public getter. The setter can have any access mode

Data types and column length

The .NET type are mapped to corresponding SQL Datatype. For Example, the String Properties are mapped to nullable nvarchar(max). The Byte array (byte[]) becomes varbinary(max) and Booleans get mapped to the bit.

The following is the DbTypeTest model with fields for various data types.

EF Core Column Data Type Conventions

The list of Data types and their columns mappings is listed below.

Data typeMappedNull ?
stringnvarchar(max)Null
decimaldecimal(18, 2)Not Null
decimal?decimal(18, 2)Null
doublefloatNot Null
double?floatNull
intintNot Null
int?intNull
boolbitNot Null
bool?bitNull
DateTimedatetimeNot Null
DateTime?datetimeNull
byte[]varbinary(max)Null
bytetinyintNot Null
byte?tinyintNull
uintbiintnot null
uint?biint ?null
shortsmallintnot null
ushortintnot null
charnvarchar(1)not null

Nullability of Column

The Nullability of the data type depends on the .NET Data type. If the .NET Data type can be null then the corresponding column is mapped as NULL. The Primary keys,  all primitive data types (like int), struct types are mapped to NOT NULL columns. All reference types like string & nullable primitive type properties are mapped as NULL columns

Primary Key Convention

Entity Framework Core does not allow you to create the tables without the primary key. It follows the convention to identify the candidate for the Primary Key. It searches any property with the name ID or <className>ID and uses it as Primary Key

EF Core Primary Key and Column Name Conventions

In the above example, we have not specified the Primary key in the model definition. But the id column from customerAddress table & cusomterID from the customer table is chosen as primary key based on the convention.

If the model contains both id & <className>ID columns, then id is chosen as Primary key

If you do not specify the primary key, then the add-migration will throw an error. For Example, try to remove the id field from the customerAddress table and check. You will get the following error

“System.InvalidOperationException: The entity type ‘CustomerAddress’ requires a primary key to be defined.”

The EF core will create the identity column if the Primary Key is defined as numeric.

The guid data type in primary key is defined as uniqueidentifier.

The older Entity Framework did not support unsigned data types. The EF Core maps the uint type bigInt datatype

Foreign Key Convention

In relational databases, data is divided between related tables. The relationship between these tables defined using the foreign keys. if you are looking for an employee working in a particular department, then you need to specify the relationship between employees and department table.

One to many Relationship

An Employee belongs to a Department. A Department can have many employees. This is a One to many relationships. This relationship is captured by adding the reference to the Department table in Employee model as shown below

Let us create models to handle

We also need to add DbSet property so that EF Core will discover these models. You can choose to add DbSet for Employee class only as the Department is referred by Employee model, hence automatically created. But, we will add DbSet for all of our models

Now drop the database recreate the migration and update the database

Note, that we did not have DepartmentID field in the Employee Model. But EFCore infers the reference to the Department table from the code  public Department Department { get; set; } as Foreign key and create the DepartmentID column in Employee table as FK

EF Core Foreign Key One to Many Relationship Conventions

The Older versions used to create the field as “Department_DepartmentID”

The one to many relations can also be specified in another way. For Example in the following model we just removed the department property from Employee table and moved it as the collection of employees in the department table

This will result in the same database structure.

And infact you should add navigational property in both the models

Many to many Relationship

Many to Many relationship is not supported yet in Entity Framework Core 2.0.

Indexes

Indexes for Foreign key is automatically created by the EF Core

EF Core Index for Foreign Key Conventions

Conclusion

The EF Core conventions provide a starting point for configuring the model. You can further  fine-tune the model using the Data Annotations & Fluent API, which we will cover in the next tutorials

2 thoughts on “Entity Framework Core Conventions”

  1. The naming conventions suggested for EF is incorrect in this article. Specifically key fields should be TablenameId not Id as in your samples.

    1. Thanks for the reply

      You are confusing naming conventions with the EF Core conventions

      If your class has any property with the name ID or ID, the EF Core automatically creates a Primary Key Fields. That’s convention followed by EF Core.

      You can use Id as the primary key naming convention for your classes. Then you can use [Key] attribute to mark it as Primary Key (if classname is different from Tablename). That’s entirely up to you.

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