Back to: ASP.NET Core Tutorials For Beginners and Professionals
Property Configuration using Entity Framework Core Fluent API
In this article, I will discuss Property Configuration using Entity Framework Core Fluent API with Examples. Please read our previous article discussing Configuring Primary Key and Composite Primary Key using Entity Framework Core Fluent API with Examples. At the end of this article, you will understand the following pointers.
- How to Configure Column Name, Type, and Order using EF Core Fluent API?
- How to Configure Column Size Using Entity Framework Core Fluent API?
- How to Configure Null or NotNull Columns using Entity Framework Core Fluent API?
- How to Ignore Table and Column Mapping using EF Core Fluent API?
How to Configure Column Name, Type, and Order using EF Core Fluent API?
As we already discussed, the Entity Framework Core default convention will create a column in the database for a property with the same name, same order, and same datatype of the Property of an Entity. We have already discussed how to override this default configuration using Entity Framework Data Annotation Attribute.
Now, we will see how we can override the default convention using Entity Framework Core Fluent API to configure Column Name, Type, and Order. To configure the column name, we need to use the HasColumnName method. To configure the column order, we need to use the HasColumnOrder method, and to configure the column data type; we need to use the HasColumnType method.
- HasColumnName(): We need to use the EF Core Fluent API HasColumnName method to configure the column name for a property. This method allows us to specify the name of the column in the database that corresponds to the property.
- HasColumnType(): We need to use the EF Core Fluent API HasColumnType method to configure the data type of a column. This method allows us to specify the data type that the column should have in the database.
- HasColumnOrder(): We need to use the EF Core Fluent API HasColumnOrder method to configure the order of a column in the database table. This method allows us to specify the position of the column relative to other columns in the table.
Let us understand this with an example. First, modify the Student Entity as follows.
namespace EFCoreCodeFirstDemo.Entities { public class Student { public int StudentId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime DateOfBirth { get; set; } } }
Next, modify the context class as follows. Here, we set the Column’s Name, Type, and Order. The Column Order will only work if we create the database table for the first time, and if we apply the Order for all the properties of the entity, else the order will not work.
using Microsoft.EntityFrameworkCore; namespace EFCoreCodeFirstDemo.Entities { public class EFCoreDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //Configuring the Connection String optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { //Configure Column Name, Order, and Type // Configure DateOfBirth column modelBuilder.Entity<Student>() .Property(p => p.DateOfBirth) .HasColumnName("DOB") .HasColumnOrder(2) .HasColumnType("datetime2"); // Configure StudentId column modelBuilder.Entity<Student>() .Property(p => p.StudentId) .HasColumnType("int") .HasColumnOrder(0); // Configure FirstName column modelBuilder.Entity<Student>() .Property(p => p.FirstName) .HasColumnType("nvarchar(50)") .HasColumnOrder(1); // Configure LastName column modelBuilder.Entity<Student>() .Property(p => p.LastName) .HasColumnOrder(3); } public DbSet<Student> Students { get; set; } } }
Note: Before Proceeding further, let us delete the EFCoreDB database using SSMS and Migration folder from our project.
With the above changes, open the Package Manager Console and Execute the add-migration and update-database commands as follows. You can give any name to your migration. Here, I am giving EFCoreDBMig1. The name that you are giving it should not be given earlier.
If you verify the database, you should see the column with the proper name, order, and type, as expected, as shown in the image below.
How to Configure Column Size Using Entity Framework Core Fluent API?
It is also possible to set the column size using Entity Framework Core Fluent API. By default, for string or byte[] properties of an entity, EF Core will set the size of the database column as max. For string properties, it will create the column as nvarchar(max), and for byte[] properties, it will create the column as varbinary(max). And for the decimal property, it will create the database column as decimal(18, 2).
To override the default size, we need to use the following HasMaxLength and HasPrecision Fluent API Methods in Entity Framework.
- HasMaxLength(int? value): To configure the size (length) of a string column, we need to use the HasMaxLength method in the Fluent API. This allows us to specify the maximum number of characters that the column can store. To configure the size (length) of a binary column (e.g., byte[]), you can use the HasMaxLength method in the Fluent API as well. However, in this case, you specify the maximum number of bytes for the column.
- HasPrecision(byte precision, byte scale): It configures the precision and scale of the property. Here, the precision parameter specifies the precision of the property, and the scale parameter specifies the scale of the property.
- IsFixedLength(): Configures the property as capable of storing only fixed-length data, such as strings.
Let us understand the above Fluent API methods with an example. So, modify the Student entity class as follows:
namespace EFCoreCodeFirstDemo.Entities { public class Student { public int StudentId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public decimal Height { get; set; } public byte[] Photo { get; set; } } }
Let us first check the default data type and size of the columns, and then we will see how we can change the size of the column using EF Core Fluent API. So, modify the context class as follows.
using Microsoft.EntityFrameworkCore; namespace EFCoreCodeFirstDemo.Entities { public class EFCoreDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //Configuring the Connection String optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { } public DbSet<Student> Students { get; set; } } }
Note: Before Proceeding further, let us delete the EFCoreDB database using SSMS and Migration folder from our project.
With the above changes, open the Package Manager Console and Execute the add-migration and update-database commands as follows. You can give any name to your migration. Here, I am giving EFCoreDBMig1. The name that you are giving it should not be given earlier.
Now, if you verify the database, you should see the database column with the default size and data type, as shown in the below image.
Next, modify the context class as follows. We have applied the HasMaxLength method on the FirstName, LastName, and Photo properties and the IsFixedLength method on the LastName property. We have also applied the HasPrecision method on the Height Property.
using Microsoft.EntityFrameworkCore; namespace EFCoreCodeFirstDemo.Entities { public class EFCoreDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //Configuring the Connection String optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { //Set FirstName column size to 50, by default data type as nvarchar i.e. variable length modelBuilder.Entity<Student>() .Property(p => p.FirstName) .HasMaxLength(50); //Set LastName column size to 50 and change datatype to nchar //IsFixedLength() change datatype from nvarchar to nchar modelBuilder.Entity<Student>() .Property(p => p.LastName) .HasMaxLength(50) .IsFixedLength(); //Set Height column size to decimal(2,2) modelBuilder.Entity<Student>() .Property(p => p.Height) .HasPrecision(2, 2); //Set Photo column size to 1024 Byte modelBuilder.Entity<Student>() .Property(p => p.Photo) .HasMaxLength(50); } public DbSet<Student> Students { get; set; } } }
With the above changes, open the Package Manager Console and Execute the add-migration and update-database commands as follows. You can give any name to your migration. Here, I am giving EFCoreDBMig2. The name that you are giving it should not be given earlier.
Now, if you verify the database, you should see the column with the appropriate size and data type as expected, as shown in the image below.
How to Configure Null or NotNull Columns using Entity Framework Core Fluent API?
In Entity Framework Core (EF Core), we can configure whether a column allows NULL values using the Fluent API. First, let us modify the Student Entity as follows for a better understanding. By default, the Entity Framework will create NULL for string Properties and NOT NULL for int types in our example.
namespace EFCoreCodeFirstDemo.Entities { public class Student { public int StudentId { get; set; } //NOT NULL By Default public string FirstName { get; set; } //NULL By Default public string MiddleName { get; set; } //NULL By Default public string LastName { get; set; } //NULL By Default } }
Configure a Column to Allow NULL Values (Nullable):
To allow a column to accept NULL values, use the IsRequired(false) method in the EF Core Fluent API configuration. By default, EF Core assumes that columns are nullable, so you only need to use this method if you want to allow NULL values explicitly.
modelBuilder.Entity<Person>() .Property(p => p.MiddleName) .IsRequired(false); // MiddleName column allows NULL values
In this example, the MiddleName column of the Person entity is configured to allow NULL values.
Configure a Column to Disallow NULL Values (NotNullable):
To make a column not nullable (i.e., disallow NULL values), omit the IsRequired method, as EF Core assumes columns are not nullable by default. However, you can explicitly use IsRequired(true) to make your intention clear.
modelBuilder.Entity<Person>() .Property(p => p.LastName) .IsRequired(); // LastName column does not allow NULL values
In this example, the LastName column of the Person entity is configured to disallow NULL values.
So, modify the context class as follows:
using Microsoft.EntityFrameworkCore; namespace EFCoreCodeFirstDemo.Entities { public class EFCoreDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //Configuring the Connection String optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { //Configure NOT NULL for FirstName column which is by default NULL modelBuilder.Entity<Student>() .Property(p => p.FirstName) .IsRequired(); //By Default True //Configure NULL for LastName column which is by default NULL modelBuilder.Entity<Student>() .Property(p => p.LastName) .IsRequired(true); //Configure NULL for MiddleName column as NULL modelBuilder.Entity<Student>() .Property(p => p.MiddleName) .IsRequired(false); } public DbSet<Student> Students { get; set; } } }
Note: Before Proceeding further, let us delete the EFCoreDB database using SSMS and Migration folder from our project.
With the above changes, open the Package Manager Console and Execute the add-migration and update-database commands as follows. You can give any name to your migration. Here, I am giving EFCoreDBMig1. The name that you are giving it should not be given earlier.
Now, verify the database, and you should see the columns with NULL and NOT NULL constraints as expected, as shown in the below image.
Configuring columns correctly according to your database schema and business requirements is important. By default, EF Core infers nullability from the CLR types of the properties in your entity classes. However, using IsRequired(false) or IsRequired(true) in the Fluent API provides explicit control over column nullability.
How to Ignore Table and Column Mapping using EF Core Fluent API?
In Entity Framework Core (EF Core), we can use the Fluent API to ignore the mapping of a table or specific columns to our entity classes. Ignoring mapping can be useful when we want to exclude certain tables or columns from being part of our EF Core model. We must use the Ignore Method to Ignore Table and Column Mapping using Entity Framework Core Fluent API.
Ignore Column Mapping using EF Core Fluent API:
To ignore the mapping of specific columns within an entity, we need to use the Ignore method for each property we want to exclude from mapping to the database. This is typically used when we have properties in our entity class that should not be persisted in the database.
The Fluent API Ignore method is used to disable property mapping to a column in the database. Let us understand this with an example. First, modify the Student Entity class as follows.
namespace EFCoreCodeFirstDemo.Entities { public class Student { public int StudentId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Branch { get; set; } } }
Now, while generating the database for the above Student Entity, we do not want to map the Branch property in the corresponding database. To Ignore the Branch property, we need to modify the context class as follows. Here, you can see on the Student entity, we call the Ignore method and specify the Branch property.
using Microsoft.EntityFrameworkCore; namespace EFCoreCodeFirstDemo.Entities { public class EFCoreDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //Configuring the Connection String optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { //Ignore the Branch Property while generating the database modelBuilder.Entity<Student>().Ignore(t => t.Branch); } public DbSet<Student> Students { get; set; } } }
Note: It’s important to note that when you ignore a column using Ignore, the property won’t be part of the database schema, and EF Core won’t generate SQL statements for it during database operations.
Note: Before Proceeding further, let us delete the EFCoreDB database using SSMS and Migration folder from our project.
With the above changes, open the Package Manager Console and Execute the add-migration and update-database commands as follows. You can give any name to your migration. Here, I am giving EFCoreDBMig1. The name that you are giving it should not be given earlier.
Now, verify the database, and you will see that the Branch column is not in the Students database, as shown in the image below. In this case, the Ignore method excludes property from the model, so it will not be mapped to the database.
Ignore Table Mapping using Entity Framework Core Fluent API:
The EF Core Fluent API Ignore Method of the modelBuilder class can also exclude the specified entity’s database mapping. Let us understand this with an example. Let us first add the following Standard Entity.
namespace EFCoreCodeFirstDemo.Entities { public class Standard { public int StandardId { get; set; } public string StandardName { get; set; } public string Description { get; set; } } }
Next, modify the context class as follows. The following example code will ensure that the Standard table is not created in the database.
using Microsoft.EntityFrameworkCore; namespace EFCoreCodeFirstDemo.Entities { public class EFCoreDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //Configuring the Connection String optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { //Ignore the Branch Property while generating the database modelBuilder.Entity<Student>().Ignore(t => t.Branch); //Ignore the Standard Entity while generating the database modelBuilder.Ignore<Standard>(); } public DbSet<Student> Students { get; set; } public DbSet<Standard> Standards { get; set; } } }
As you can see in the above code, we have created Standard Entity as a DbSet property. But then we used the Ignore method and specified the Standard Entity, which will exclude the Standard entity while generating the database.
Note: Before Proceeding further, let us delete the EFCoreDB database using SSMS and Migration folder from our project.
With the above changes, open the Package Manager Console and Execute the add-migration and update-database commands as follows. You can give any name to your migration. Here, I am giving EFCoreDBMig1. The name that you are giving it should not be given earlier.
Now, verify the database, and you should see only the Students table but not the Standard table in the database, as shown in the image below.
In the next article, I will discuss Bulk Operations using Entity Framework Core with Examples. In this article, I try to explain Property Configuration using Entity Framework Core Fluent API with Examples. I hope you enjoyed this Property Configuration using Entity Framework Core Fluent API article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.