EF Core Sequence — Complete Guide
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
Right
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
HasSequencefor cross-table sequence generators. - Sequences are not tied to a specific table — they generate globally unique numbers.
- Use
HasDefaultValueSqlwithNEXT VALUE FORto 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
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - 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.Learn more at DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro