Fluent APIs

Customizing configuration

EF Core uses a set of conventions - heuristics that look for common patterns. There might be situations where we would want to customize the configuration when the conventions do not serve our purpose.

The model can then be customized using:

  • mapping attributes (also known as data annotations) and/or

  • calls to the ModelBuilder methods (also known as fluent API) in OnModelCreating

  • both of which will override the configuration performed by conventions!

  • Most configuration can be applied to a model targeting any data store.

Providers may also enable configuration that is specific to a particular data store, and they can also ignore configuration that is not supported or not applicable.

Use fluent API to configure a model

You can override the OnModelCreating method in your derived context and use the fluent API to configure your model. This is the most powerful method of configuration and allows configuration to be specified without modifying your entity classes.

Fluent API configuration has the highest precedence and will override conventions and data annotations!

Configure maximum length

Let us use fluent API to configure the maximum possible length for the name field of our student entity. In order to do so make the following changes in the context file:

Add the method shown below to MyContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
        .Property(i => i.Name)                
        .HasMaxLength(5);
}

When we apply a new constraint, unless we apply a migration the changes do not reflect!

Creating and applying migration

dotnet ef migrations add name_length
dotnet ef database update

Now modify the program file and replace the code as shown below:

using EFGetStarted;
using Microsoft.EntityFrameworkCore;
using System;

var db = new MyContext();

var s1 = new Student() { Name = "Krish", City = "Bangalore" };
db.Students.Add(s1);
db.SaveChanges();
Console.WriteLine("S1 Done");

var s2 = new Student() { Name = "Anirudh",City = "Delhi"};
db.Students.Add(s2);
db.SaveChanges();

Console.WriteLine("S2 Done");

Console.WriteLine("Press any key to exit");
Console.ReadKey();

Run the application

When we run the application, we see that the first student was inserted but the second one was not and the exception we get looked like this

...
Inner Exception 1:
SqlException: String or binary data would be truncated.
...

Last updated