I have the following scenario:
A business logic function that uses ef6 checks if a record already exists. If the record does not exists, it is inserted on the databa
I would harness the concurrency handling built into Entity Framework rather than write my own logic.
You add a concurrency token to the database. Typically this would be a RowVersion field:
Using FluentAPI:
modelBuilder.Entity()
.Property(t => t.Timestamp)
.IsRowVersion();
Using Data Annotations:
[Timestamp]
public byte[] RowVersion { get; set; }
Typically you then handle the DbUpdateConcurrencyException thrown when there is a problem:
using (var context = new SchoolDBEntities())
{
try
{
context.Entry(student1WithUser2).State = EntityState.Modified;
context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
Console.WriteLine("Optimistic Concurrency exception occured");
}
}
References:
Configuring a concurrency token
Handling concurrency in Entity Framework
Optimistic concurrency patterns using Entity Framework
EDIT Just realised that I have misread your question. You aren't really talking about concurrency here, as your question title suggests. You just want to ensure that a record's natural key is unique. The way to do that is over here: https://stackoverflow.com/a/18736484/150342