The Entity Framework Conventions (or code first conventions) are default rules, which the Entity Framework uses 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. Code-First conventions are defined in System.Data.Entity.ModelConfiguration.Conventions namespace
In this tutorial, we will take a look at the Entity Framework Code First Conventions supported by Entity Framework.
Table of Contents
Entity Framework Code First Conventions
The Code first 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 code first conventions or Entity Framework naming conventions.
Open the Project which we created in the tutorial Entity framework Relationships. You can download the code from this link
Type Discovery
In our last tutorial, we created domain model with the name Employee. We then created the DBContext class EFContext with the DbSet property for the Employee class. EF Automatically detected the Employee class and created the Employee Table.
Entity Framework looks at the types that expose the DbSet Property. It does this by using the reflection (type discovery). It then creates the tables for these types. It also includes any referenced types that do not expose the DbSet Property. It also creates all the types of inheritance hierarchy if the base class exposes the DbSet Property.
Open the project and take a look at the models.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | public class Employee { public int EmployeeID { get; set; } public string Name { get; set; } //Navigation property Returns the Employee Address public virtual EmployeeAddress EmployeeAddress { get; set; } //Navigation property Returns the Employee Department public virtual Department Department { get; set; } //Navigational Property for Grade public virtual Grade Grade { get; set; } //GradeID is defined here. EF will mark this as ForeignKey public int GradeID { get; set; } //Navigation property public virtual ICollection<Project> Projects { get; set; } } public class EmployeeAddress { //Defining the ForeignKey [Key, ForeignKey("Employee")] public int EmployeeID { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } //Navigation property Returns the Employee object public virtual Employee Employee { get; set; } } public class Department { public int DepartmentID { get; set; } public string Name { get; set; } //Navigational Property. Returns the collection of employee public virtual ICollection<Employee> Employees { get; set; } } public class Grade { public int GradeID { get; set; } public string Name { get; set; } //Navigation property public virtual ICollection<Employee> Employees { get; set; } } public class Project { public int ProjectID { get; set; } public string Name { get; set; } //Navigation property public virtual ICollection<Employee> Employees { get; set; } } |
Our Context class looks like this
1 2 3 4 5 6 7 8 9 10 | public class EFContext : DbContext { public EFContext() : base("EFDatabase") { Database.SetInitializer(new DropCreateDatabaseAlways()); } public DbSet Employees { get; set; } } |
We have defined DbSet Property for the Employee Table. Hence code first creates a table Employees.
We have not defined DbSet properties for the other domain models like EmployeeAddress, Department, and Project. Entity Framework Creates these tables because they are referenced by the employee class. This is recursive. If any of these has reference to any other types, those tables also will be created.
Table Name Convention
Code First creates the tables using the pluralized forms of entity class names. In the above example, the table name for employee class is employees.
It uses the English language based rules for Pluralization. Usually, it just adds or removes “s” and “es” in the end. But in some cases ( Person becomes People) it gets little complicated.
Column Names
Columns are named after the property name. By Convention, all public properties, which has a getter and a setter will be included in the mode. Columns names are not pluralized.
Data types and column length
The String Properties are mapped to nullable nvarchar(max). The Byte array (byte[]) becomes varbinary(max) and Booleans get mapped to bit. The complete list of Data types and their columns mappings are listed below.
Data Type | Mapped to |
---|---|
string | nvarchar(max) |
decimal | decimal(18, 2), not null |
decimal? | decimal(18, 2), null |
double | float, not null |
double? | float, null |
int | int, not null |
int? | int, null |
bool | bit, not null |
bool? | bit, null |
DateTime | datetime, not null |
DateTime ? | datetime, null |
byte[] | varbinary(max) |
Primary Key
Entity Framework Code First 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. There is no restriction on the data type of the Primary key except for the unsigned data types.
If Code first does not find the Primary key it will throw the ModelValidationException
Foreign Key Convention
Foreign Key is used to define the relationship between tables in the database. For Example, the employee working in a department is a relationship. This relationship is expressed by creating a DepartmentID field in the employee table and marking it as Foreign Key
The relationships in EF is defined using the navigational property. The EF infers the relationship and creates the relevant Foreign Key in the database. We discussed the Relationships in entity framework in this tutorial
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 in the model as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Employee { public int EmployeeID { get; set; } public string EmployeeName { get; set; } //Navigation property public Department Department { get; set; } } public class Department { public int DepartmentID { get; set; } public string DepartmentName { get; set; } //Navigation property public ICollection<Employee> Employeees { get; set; } } |
The above model defines the one to many relationships between the Employee table and Department table. The Employee table has a Department property, which refers to the Department. The Department has an Employees property which is a collection of Employees. These two properties are referred to as the navigational property
The Entity Framework infers this as one to many relationships between Employee and Department and automatically inserts the Foreign Key in the dependent table.
The above results in the creation of Foreign Key named as Department_DepartmentID in the employee table. The Entity Framework uses <navigation property Name> _ <primary key property name of navigation property type;> to name the navigation property.
But, if you add DepartmentID property in employee model, the EF will use that field as shown in image below
Many to many Relationship
We have a Many to Many relationships between Employee and Project domain model. An Employee can handle many projects and Projects can have many employees. In such
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Employee { public int EmployeeID { get; set; } public string EmployeeName { get; set; } //Navigation property public virtual ICollection<Project> Projects { get; set; } } public class Project { public int ProjectID { get; set; } public string Name { get; set; } //Navigation property public virtual ICollection<Employee> Employees { get; set; } } |
The Entity Framework Code first by convention creates the Join table to handle the Many to many relationships.
In our example, the join table ProjectEmployees is added by the Code first to handle the Many to Many relationships between Employee and Project domain models.
Conclusion
The Code First conventions provide a starting point for the model. You can then fine-tune these conventions using Configuration.