How to Create a Fluent API in C# Mitesh Shahs Blog
- October 19, 2021
- Posted by: nader
- Category: Software development
Contents
In fluent APIs like StringBuilder discussed above, any combination of method calls can compile, even if it breaks the protocol. To avoid run-time errors, we have to state the protocol details in the class documentation . Once this line of code has been added, you no longer need to remember to add new type configuration registrations to the OnModelCreating method as your model grows.
To access Fluent API you need to override the OnModelCreating method in DbContext. Let’s take a look at a simple example in which we will rename the column name in student table from FirstMidName to FirstName as shown in the following code. C# uses fluent programming extensively in LINQ to build queries using “standard query operators”. To write Fluent API configurations, override the OnModelCreating() method of DbContext in a context class, as shown below. The price list will be placed directly in the code since we don’t use a database or another data reference, and we intend to make the example as simple as possible. But it is worth stressing that, in a natural environment, this information would be in a database or a service.
- In this example, the DateCreated property of the Order entity is configured as Required , is mapped to a SQL Server Date type and has a default value applied.
- Let’s take a look at a simple example in which we will rename the column name in student table from FirstMidName to FirstName as shown in the following code.
- The foreign key is defined on the table that represents the many end of the relationship.
- Here I am using StringBuilder to store the actual string content of the dockerfile and the setters are essentially just adding content to this string builder.
- So when User2 tries to update same product it’s query becomes as shown below which will return zero records because User1 already committed ProductName as “Product 2”.
In this example, the DateCreated property of the Order entity is configured as Required , is mapped to a SQL Server Date type and has a default value applied. Each method call returns a type that exposes its own set of methods which is what enables the chaining of methods. Often, the type returned from the method call is the same instance as the one on which the method is called.
What is a Fluent-API?
We know that, in a software project, nothing replaces good documentation. However, it is also necessary to pay attention to how intuitive the written code is. After all, the simpler and more natural the code is, the better its experience for users. If you want to check the new possible way to create Many-to-Many Relationships using EF Core 5.0 , check the article about this subject by clicking here.

For example, you need to add details of Japnese products in Japnese language characters. Fluent API Ignore method can be use to configure Not mapped columns. The following column configures DiscountAmount column as not to be mapped.
Update or create a related record
In a one-to-one relationship, the primary key acts additionally as a foreign key and there is no separate foreign key column for either table. In Entity Framework, by default Code First will create a column for a property with the same name, order, and datatype. But you can also override this convention, as shown in the following code. You can use the HasDefaultSchema method on DbModelBuilder to specify the database schema to use for all tables, stored procedures, etc. Instances of the entity type will be able to be saved to the database without this relationship being specified.
They were using this library called Fluent Assertions to write their assertions, and although it doesn’t fundamentally change the test or performance, the code looks readable. There is a similar library to write validations as well, aptly named Fluent Validation. To configure many-to-many relationship between Student and Course, you can use Fluent API as shown in the following code.
If, for example, you choose a chicken sandwich, the sides will be suggested considering the chosen dish and so on. That’s why, in this article, we’ll introduce the topic and show you how to create a fluid API from the Fluent-API concept. In the simple “programming rule”, in which we will forget everything we have to remember, Why Python is a Great First Language Trinket Blog an API that “forces” you to remember is crucial proof of failure. Columns that are computed or dependant on other columns like DiscountAmount which might maybe dependant on Price and CustomerType to calculate final amount of discount. I’ll continue with the common example of making out an order for a customer.
Connect or create a record
Certainly chaining is a common technique to use with fluent interfaces, but true fluency is much more than that. One of the problems of methods in a fluent https://forexaggregator.com/ interface is that they don’t make much sense on their own. Looking at a method browser of method by method documentation doesn’t show much sense towith.

Viscous Interface, where due to the above 3, the interface loses its fluency over time. Let’s try to see the order of methods that we can call using a state diagram . We are going to use Interfaces to solve all the problems listed above.
Using Fluent API in EF Core code first
For example, the IsRequired method above is exposed by the PropertyBuilder class. The return type of this method is an instance of the PropertyBuilder class, so once the method has performed its task, it ends simply with return this;. EF Core follows conventions to generate the database and the tables. These conventions are the rules to create the model, based in the entities classes. With Fluent API we can override these configurations and explicitly defined the configuration that we want to set in the tables in the database.
The Property method is used to configure attributes for each property belonging to an entity or complex type. The Property method is used to obtain a configuration object for a given property. You can also map and configure the properties of your domain classes using Fluent API. With default convention, Code First will create the database tables with the name of DbSet properties in the context class such as Courses, Enrollments and Students. But if you want different table names then you can override this convention and can provide a different table name than the DbSet properties, as shown in the following code.
When you define a one-to-one relationship in your model, you use a reference navigation property in each class. In database, both tables can have only one record on either side of the relationship. Each primary key value relates to only one record in the related table. Like with StringBuilder, and builders in general, having the fluent methods return the current object is the simplest way to go. Entity Framework Fluent API is used to configure domain classes to override conventions.
A complete API invocation ends in accepting states, marked with double-line border; in our case, we allow build() to be called only after the body has been set. Besides, of course, proper documentation, the usability of an API is greatly influenced by its design. In this post we discuss fluent APIs, which are produced by a funky and popular design technique. We learn what fluent API is, how it benefits the programmer, and how to compose expressive fluent APIs.
We also show the applicability of fluent APIs to domain-specific languages. You can see when the database is generated, the table and columns name are created as specified in the above code. Below are the Student and Enrollment which has one-to-many relationship, but the foreign key in Enrollment table is not following the default Code First conventions.
