Skip to content

EF Core Sequence — Complete Guide

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about EF Core Sequence. We cover key concepts, practical examples, and best practices.

You use auto-increment identity columns, but you need a unique number that spans multiple tables (e.g., invoice numbers shared between orders and refunds).

Wrong

public class Order { public int OrderNumber { get; set; } } // identity, per-table
public class Refund { public int RefundNumber { get; set; } } // identity, per-table
// Order 42 and Refund 42 — collision in external references
protected override void OnModelCreating(ModelBuilder builder)
{
    builder.HasSequence<int>("TransactionNumbers")
        .StartsAt(1000)
        .IncrementsBy(1);
}

public class Order
{
    public int Id { get; set; }
    public int TransactionNumber { get; set; }
}

public class Refund
{
    public int Id { get; set; }
    public int TransactionNumber { get; set; }
}

// Configure both to use the sequence
builder.Entity<Order>()
    .Property(e => e.TransactionNumber)
    .HasDefaultValueSql("NEXT VALUE FOR TransactionNumbers");

builder.Entity<Refund>()
    .Property(e => e.TransactionNumber)
    .HasDefaultValueSql("NEXT VALUE FOR TransactionNumbers");

Prevention

  • Use HasSequence for cross-table sequence generators.
  • Sequences are not tied to a specific table — they generate globally unique numbers.
  • Use HasDefaultValueSql with NEXT VALUE FOR to consume from sequence.
  • Sequences can have min/max values, cycle, and cache settings.
  • Unlike identity columns, sequences can be reserved in advance.

Common Mistakes with core sequence

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

What is the difference between identity and sequence?

Identity is per-table auto-increment. Sequence is a database-wide number generator that can be used across tables.
Can I use sequences with non-integer types?

Yes. Sequences can produce bigint, decimal, or smallint values.

Are sequences transactional?

No. Once a sequence value is generated, it is not rolled back even if the transaction fails.

Learn more at DodaTech.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro