Handling Concurrency in EF Core in ASP.NET Core

πŸ’‘ Concept Name

EF Core Concurrency Handling

πŸ“˜ Quick Intro

Concurrency conflicts happen when two users attempt to update the same data at the same time. Entity Framework Core provides mechanisms like RowVersion or concurrency tokens to detect and resolve these conflicts gracefully.

🧠 Analogy / Short Story

Imagine two people editing the same Google Doc without real-time sync. One finishes editing and clicks "save," while the other is still typing. If the second person saves after the first, they might unknowingly overwrite changes. EF Core prevents this kind of overwriting by checking if the content was changed between reads and writes.

πŸ”§ Technical Explanation

EF Core uses Optimistic Concurrency Control (OCC) by default. You add a [Timestamp] or [ConcurrencyCheck] attribute to a column like a byte[] RowVersion or a timestamp. EF Core includes that value in the WHERE clause during updates. If no rows are affected, a DbUpdateConcurrencyException is thrown, which you can catch and handle.

🎯 Purpose & Use Case

  • βœ… Prevent lost updates in collaborative environments
  • βœ… Detect changes before saving conflicting updates
  • βœ… Ensure data integrity in multi-user applications
  • βœ… Trigger custom merge logic in case of conflict

πŸ’» Real Code Example

Model Example:


public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }
}
            

Update with Concurrency Handling:


try
{
    dbContext.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
    // Handle concurrency conflict
    foreach (var entry in ex.Entries)
    {
        // Refresh values, show merge UI, etc.
    }
}
            

❓ Interview Q&A

Q1: What is concurrency in EF Core?
A: When multiple users try to update the same data simultaneously, causing potential conflicts.

Q2: What is optimistic concurrency?

A: A strategy where conflicts are detected at the time of saving, assuming they are rare.

Q3: What attribute is used for concurrency tokens?

A: [Timestamp] or [ConcurrencyCheck]

Q4: What happens when concurrency conflict is detected?

A: EF throws DbUpdateConcurrencyException

Q5: How can you resolve concurrency conflicts?

A: Catch the exception and implement conflict resolution like reload or merge.

Q6: Can you use strings for concurrency tokens?

A: Yes, but byte[] (RowVersion) is preferred for precision.

Q7: Which method throws the exception?

A: SaveChanges()

Q8: Is concurrency handling enabled by default?

A: Only if you explicitly mark the property.

Q9: Difference between pessimistic and optimistic concurrency?

A: Pessimistic locks resources, optimistic assumes no conflict but verifies on save.

Q10: Can EF Core auto-merge changes?

A: No, you must write custom logic on conflict.

πŸ“ MCQs

Which attribute enables concurrency tracking in EF Core?

  • [Key]
  • [ForeignKey]
  • [Timestamp] ✔
  • [Required]

What exception is thrown on a concurrency conflict?

  • DbUpdateException
  • ConcurrencyException
  • DbConcurrencyUpdateException
  • DbUpdateConcurrencyException ✔

Optimistic concurrency assumes:

  • Conflicts are frequent
  • Conflicts are rare ✔
  • Data is always locked
  • Data is shared via tokens

Where is the concurrency token value checked?

  • SELECT clause
  • INSERT clause
  • WHERE clause ✔
  • ORDER BY clause

Which method is used to catch concurrency errors?

  • AddAsync
  • Find
  • SaveChanges ✔
  • Remove

What type is commonly used for RowVersion?

  • string
  • int
  • DateTime
  • byte[] ✔

Is concurrency checking automatic for all fields?

  • Yes
  • No ✔

Which concurrency strategy locks resources in advance?

  • Optimistic
  • Pessimistic ✔
  • Aggressive
  • Passive

EF Core concurrency helps prevent:

  • SQL Injection
  • Deadlocks
  • Lost Updates ✔
  • Duplicate Keys

Can concurrency tokens be nullable?

  • Yes ✔
  • No

πŸ’‘ Bonus Insight

Concurrency handling is critical in enterprise-grade multi-user systems. EF Core’s built-in mechanisms save developers from race conditions and silent overwrites β€” essential for business apps that require high data integrity.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: