Fluent API in Entity Framework Core Example

In Entity framework core fluent api is model builder class, that provides many different mechanism to configure model and entity, there are many options other than data annotation attributes, in entity framework we use both attribute mapping and model builder class.

All model builder related changes are done inside the OnModelCreating method; in model builder we will configure all entities and properties.

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
            
base.OnModelCreating(modelBuilder);
}

Configure model for one particular schema, so if there are multiple schema in database, then you know which one to target, simply use HasDefaultSchema method.

modelBuilder.HasDefaultSchema("marketing");

To explain various types of configurations and relationships, let’s create some objects first, so it will be easy to explain.

[Table("tbOrder")]
public class Order
{
	[Key]
	public int OrderId { get; set; }

	[Column("clientId")]
	public int UserId { get; set; }

     /* EF Relations */
	public Client Client { get; set; }

	public string Description { get; set; }

     /* EF Relations */
	public ICollection<OrderItem> Orderlists { get; set; }
}

In above order object you can see order to client (one to one relation) and order to orderitems (one to many relationship), now we see how to define relationship using fluent API.

[Table("tbOrderItem")]
public class OrderItem
{
	[Key]
	[Column("oItemId")]
	
	public int OrderItemId { get; set; }
	
	public int OrderId { get; set; }

     /* EF Relations */
	public Order Order { get; set; }

	
	public int ProductId { get; set; }

	public int Quantity { get; set; }

	public decimal UnitPrice { get; set; }   
}

Let's design OrderItem object with a property Order.

One to many relationships configuration

Now based on above two entities lets write the configuration using fluent API, notice one to many replations using WithMany(oi => oi.Orderlists), and telling the model builder that OrderItem has one order HasOne<Order>(o => o.Order) associated with it with the foreign key.

public DbSet<Client> tbClient { get; set; }
public DbSet<Order> tbOrder { get; set; }
public DbSet<OrderItem> tbOrderItem { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OrderItem>()
 .HasOne<Order>(o => o.Order)
 .WithMany(oi => oi.Orderlists);
}

The same above one to many relation also can be written differently, using .HasMany<OrderItem>(oi => oi.Orderlists) and .WithOne(o => o.Order)

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>()
.HasMany<OrderItem>(oi => oi.Orderlists)
.WithOne(o => o.Order);
}
Primary composite Keys configuration in EF Core

Entity Framework Core supports composite keys configuration - composite keys are primary key values generated from two or more fields in the sql database.

There is no additional method to configure composite keys in entity framework core; we need to use the same HasKey method to configure multiple fields as composite keys.

Suppose we have a order history table in sql database with composite key OrderId and ProductId, so we have created following entity in c# code, now we need to configure order id and product id as composite key.

public class OrderHistory
{
  [Key]
  public int OrderId { get; set; }

  [Key]
  public int ProductId { get; set; }
}

Now we need to use the same HasKey method like HasKey(o => new { o.OrderId, o.ProductId }); to configure multiple fields.

protected override void OnModelCreating(ModelBuilder builder)
{
   builder.Entity<OrderHistory>().HasKey(o => new {
     o.OrderId, o.ProductId
   });
}

You may be interested in following posts!

 
EF Core Fluent API
Learn entity framework orm using c#, entity framework core and earlier version of entity framework, all tutorials are written in c#.
Entity Framework Interview Questions

SQL interview questions
Entity Framework C# Examples | Join .Net C# Course