I have the following code that I am trying to update ClientAccount using ef core but they Concurrency Check fails:
public class ClientAccount
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Required]
[ConcurrencyCheck]
public double Balance { get; set; }
[Required]
public DateTime DateTimeCreated { get; set; }
[Required]
public DateTime DateTimeUpdated { get; set; }
}
public class ClientRepository
{
private readonly MyContext context;
public ClientRepository(MyContext context)
{
this.context = context;
}
public ClientAccount GetClientAccount()
{
return (from client in context.ClientAccount
select client).SingleOrDefault();
}
public void Update(ClientAccount client)
{
context.Update(client);
context.Entry(client).Property(x => x.DateTimeCreated).IsModified = false;
}
}
public class ClientService
{
private readonly ClientRepository clientRepository;
private readonly IUnitOfWork unitOfWork;
public ClientService(ClientRepository clientRepository,
IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
this.clientRepository = clientRepository;
}
public void Update(ClientAccount clientAccount)
{
if (clientAccount == null)
return;
try
{
ClientAccount existingClient = clientRepository.GetClientAccount();
if (existingClient == null)
{
// COde to create client
}
else
{
existingClient.AvailableFunds = clientAccount.Balance;
existingClient.DateTimeUpdated = DateTime.UtcNow;
clientRepository.Update(existingClient);
}
unitOfWork.Commit();
}
catch (DbUpdateConcurrencyException ex)
{
}
}
}
Problem is that DbUpdateConcurrencyException is not fired whenever two threads are trying to update it at the same time and thus I don't have expected functionality.
I don't understand what is the problem here as marking the property with ConcurrencyCheck attribute should do the work.