EF Feature CTP5 – Code First Fluent API
One of Code First main features is the Fluent API. This API can help you to configure the model in order to shape it (and the database) better. In this post I’m going to show a simple example for how to use the Fluent API. Pay attention that the details I provide might change in the future since its only a CTP and not a release.
The Example Model
In the example I’m going to use the following model:
Fluent API Example
After you create your model there are a lot of ways to configure the model using the Fluent API. The main place to do that is in the OnModelCreating method which you override in the DbContext. That method gets a ModelBuilder instance which can be used to configure the model. The following example shows how to write some configuration with the API:
What is Configured?
Lets explain what you see in the above code. When I want to configure an entity I use the Entity method with the entity as a generic parameter. Then I’m exposed to the Fluent API and can start configure my model.
In the first line I configure the Name property of the department as required and with length of no more than 50 characters.
In the second line I configure the DepartmentID as non database generated (since by default all the ID will be database generated).
The third line creates a one to many relation between the department and its course collection. You first use the HasMany to indicate the many side and then use the WithRequired to indicate the one side of the relation. The HasForeignKey indicate the foreign key on the many side. The last method, WillCascadeOnDelete, will add cascade delete on the entity graph.
The forth line will force the model to ignore the administrator property of the department and therefore it won’t be generated in the database.
The fifth line indicates that the Title property is required and that in the database the column name will be Name instead of Title.
Here is a simple example of creating data and inserting it to the database:
Running this example will generate a new database by the name ClassLibrary1.SchoolEntities with all the configurations that were written in the OnModelCreating method. If you want to change the generated database name (which is taken from the namespace and context name by default) you need to create a constructor to the DbContext with a call for the base constructor that gets a string as parameter:
Lets sum up, Code First has a very interesting feature of fluent API. The fluent API for model configuration is easy to understand and use. In this post I showed and explain a small portion of the API.