Fluent API Configuration:
We've already learned that using the Dataanotations feature to override the Code-first default conventions, let's now learn the fluent API.
The fluent API is another way to configure the domain class, which provides more configuration methods than the DataAnnotations feature, and the following table is the type mappings supported by the fluent API.
type of mapping |
Configuration Database |
Model (Model-wide) mapping |
- Setting the default Schema
- Set Custom Conventions
|
Entity mapping |
- Set up a single table or multiple tables and set up schemas
- Setting Complex Types
- Set inheritance Hierarchy
|
Property mapping |
- Set column, column name, type, whether nullable, size, sort
- Set Concurrent Columns
- Set FOREIGN key columns
- Configuring relationships
|
Below, we start using the Fluent API to configure the Realm class.
We first create student and standard two domain classes, also create DbContext class, DbContext class has a onmodelcreating method, here we in its inheritance class to overwrite it.
The code is as follows:
Public classSchoolcontext:dbcontext { PublicSchooldbcontext ():Base() { } PublicDbset<student> Students {Get;Set; } PublicDbset<standard> Standards {Get;Set; } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {//Configure domain classes using ModelBuilder here Base. Onmodelcreating (ModelBuilder); }}
When using the fluent API to configure the domain class, all the configuration code is written in the Onmodelcreating method, and all domain classes can write their initialization code in this method. When the program is initialized, the dataannotation and fluent APIs are prioritized: Fluent API > DataAnnotations > Default Conventions.
The Dbmodelbuilder class contains important properties and methods for configuration, and for more details, go to the MSDN documentation.
Next, let's talk about some common fluent API configuration methods. (not to be continued)
EntityFramework Code-first Easy Tutorial (vii)-------the domain class configuration fluent API