Entity Framework Core Configurations allow us to override the default conventions in order to create database schema and mappings in the way we want. We already saw the concept of Conventions in Entity Framework Core where we understood how default conventions work. If we want to override the conventions then apply the configurations and customize the EF Core model to database mappings.
Page Contents
There are 2 Entity Framework Core Configuration Methods:
Let us understand them one by one.
These are the .NET Attributes that can be applied to the domain classes and their properties. The Data Annotation attributes are included in separate namespace called System.ComponentModel.DataAnnotations.
Let me demonstrate how to apply these Data Annotation Attributes to the domain classes in order to configure database tables and override the default Conventions of Entity Framework Core.
In the below code we have applied Data Annotation Attributes to the 2 domain classes (Country & City) and their properties.
[Table("TBL_City")]
public class City
{
[Key]
public int KeyId { get; set; }
[Column("CityName", TypeName = "varchar(25)")]
public string Name { get; set; }
[NotMapped]
public int Population { get; set; }
[ForeignKey("FKid")]
public Country Country { get; set; }
}
[Table("TBL_Country")]
public class Country
{
[Key]
public int KeyId { get; set; }
[MaxLength(20)]
public string Name { get; set; }
}
Once we apply Entity Framework Core Migration then 2 database tables will be created due to [Table("Name")]
attribute on the classes. These tables are:
The table called TBL_City has:
The table called TBL_Country has:
See the below image which shows the snapshot of these 2 database tables.
Attribute | Description |
---|---|
Table | Applied on entity class to give a name to database table. |
Column | Applied on a property to give column name, order and data type. |
Key | Sets the property as primary key for the table. |
ForeignKey | Applied to a property to mark it as foreign key. |
NotMapped | Can be applied to entity class or property for not generating a corresponding table or column in the database. |
MaxLength | Sets the max length for the table column. |
Required | Can be applied on properties to make the corresponding column on the table as not null. |
Another way to configure domain classes is by using Entity Framework Fluent API. You will learn about Fluent API by reading these 4 tutorials.
Download the source code: