Fluent API in Code-first:
We have seen different dataannotations attributes in the previous sections to override default Code-first conventions. Here, we'll learn about the Fluent API.
Fluent API is another-configure your domain classes. Fluent API provides more functionality for configuration than dataannotations. Fluent API supports the following types of mappings.
mappings |
to Database |
model-wide Mapping |
- Set default Schema
- set Custom convetions
|
Entity Mapping |
- to single or multiple Tables and Schema
- to Complex type
- inheritance hierarchies
|
Property Ma Pping |
- to column, column Name, column Type, Nullable or not Null Column, column size, column S Order
- to Concurrency column
- to Foreign key column
- to configure relationships
|
Let's get started with Fluent API. First of all, let's create Student & standard domain classes and context class as we've created in the simple code-f Irst Example section. Now, the override onmodelcreating method of DBContext in a context class, as shown below.
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); }}
Now, the all your configuration code using the Fluent API should is in Onmodelcreating method. Dbmodelbuilder is a main class on which you can configure all your domain classes because at this point, all your domain C Lasses would has initialized.
You can also use Dataannotation and Fluent APIs at the same time. Code-first gives precedence to Fluent API > Data annotations > Default conventions.
Dbmodelbuilder class includes important properties and methods to configure. Visit MSDN For more information on Dbmodelbulder class.
Let's start to configure entities using Fluent API in the next section.
Entity Framework Code-first (Ten): Fluent API