This is my example app scenario:
public class SampleDbContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=ExampleUserDB;Trusted_Connection=True;");
}
}
public class User
{
public int Id { get; set; }
public bool AnalyseInProgress { get; set; }
public bool Analysed { get; set; }
}
public class UserService
{
public User GetUser()
{
using (var context = new SampleDbContext())
{
using (var transaction = context.Database.BeginTransaction())
{
var entity = context.Users
.Where(x => !x.Analysed)
.Where(x => !x.AnalyseInProgress)
.FirstOrDefault();
entity.AnalyseInProgress = true;
context.SaveChanges();
return entity;
transaction.Commit();
}
}
}
public void MarkUserAsAnalysed(int id)
{
using (var context = new SampleDbContext())
{
var entity = context.Users
.Find(id);
entity.Analysed = true;
context.SaveChanges();
}
}
}
By adding transaction and AnalyseInProgress property, I wanted to prevent returning the same user to multiple applications, if they call UserService.GetUser at the same time.
Unfortunately, it doesn't work as I expected. Sometimes, service returns the same user. Is there any built-in solution to that?
Thanks.