In this lesson, you will learn how to determine whether your database should automatically generate unique identifiers for your entities or if your application logic should assign them manually.
Choosing Your Primary Key Strategy
In Entity Framework Core, every entity must have a primary key. Deciding how that key gets its value is a critical design choice that affects performance, security, and data integrity.
Database-Generated Keys
By default, EF Core assumes that numeric keys (like int or long) are identity columns generated by the database. When you add a new entity to the DbContext, the database assigns the next available number upon insertion. This is the most common pattern for internal IDs because it is simple and prevents conflicts.
To explicitly ensure this behavior in your OnModelCreating method using the Fluent API:
modelBuilder.Entity<Product>()
.Property(p => p.Id)
.ValueGeneratedOnAdd();
Manual Assignment
Sometimes, your business requirements dictate that you control the primary key. This is common when using Guid values generated in the application layer, or when importing data with existing natural keys (like a SKU or an email address).
If you want to manage the ID yourself, you must instruct EF Core not to wait for the database to provide a value:
modelBuilder.Entity<User>()
.Property(u => u.Id)
.ValueGeneratedNever();
If you choose manual assignment, your application logic is responsible for ensuring the uniqueness of these keys before calling SaveChanges(). If you fail to provide a value or provide one that already exists, the database will throw an exception.
Which one to choose?
- Use Database Generation when you want to minimize complexity and ensure sequential, conflict-free integers.
- Use Manual Assignment when you need high-performance GUIDs that can be generated offline or when you need to maintain consistency across distributed systems before the record is persisted.
Key Takeaway: Choose database-generated keys for simplicity and sequence-guaranteed uniqueness, or use manual assignment when your application domain requires full control over entity identification before reaching the database.