In Entity Framework you have to run the code with in a DbContextTransaction scope. In this example we run within the DbContextTransaction scope, Get a lock & finally commit at the end.
public bool MySampleMethod(Model instance)
{
using (DbContextTransaction scope = _context.Database.BeginTransaction())
{
bool sent;
_context.Database.ExecuteSqlCommand("SELECT TOP 1 Id FROM MySampleTable WITH (TABLOCKX, HOLDLOCK)");
sent = _context.MySampleTable.Any(n => n.Guid == instance.Guid &&
n.PublishedDate ==
instance.PublishedDate &&
n.UserId == instance.UserId &&
n.RegistrationId ==
instance.RegistrationId);
if (!sent)
{
DoFurtherProcessing(instance);
}
scope.Commit();
}
return sent;
}
public bool MySampleMethod(Model instance)
{
using (DbContextTransaction scope = _context.Database.BeginTransaction())
{
bool sent;
_context.Database.ExecuteSqlCommand("SELECT TOP 1 Id FROM MySampleTable WITH (TABLOCKX, HOLDLOCK)");
sent = _context.MySampleTable.Any(n => n.Guid == instance.Guid &&
n.PublishedDate ==
instance.PublishedDate &&
n.UserId == instance.UserId &&
n.RegistrationId ==
instance.RegistrationId);
if (!sent)
{
DoFurtherProcessing(instance);
}
scope.Commit();
}
return sent;
}
No comments:
Post a Comment