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) inOnModelCreating
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
When we apply a new constraint, unless we apply a migration the changes do not reflect!
Creating and applying migration
Now modify the program file and replace the code as shown below:
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
Last updated