Robin Nehra
Robin Nehra

Reputation: 1

SQL to Entity Framework

I'm using Azure SQL database and Entity Framework for performing database operations on it.

How can I convert this SQL query to Entity Framework ?

begin tran set transaction isolation level serializable
go

select top 1 * from Employee with (UPDLOCK) where EmpID = @id;

......

commit

I want to lock a row from other threads when some thread is reading it and perform some operation on it.

I cannot use stored procedures as I'm using Azure SQL database.

Upvotes: 0

Views: 207

Answers (1)

divega
divega

Reputation: 6476

I don't know why you could not use a stored procedure for this. As marc_s mentioned Azure SQL DB supports stored procedures. That said you can always execute the query from EF if you want. EF does not support specifying query hints for LINQ queries, so the easiest would be to use raw SQL execution APIs. It would look like this using EF6:

using (var context = new MyContext()) 
{ 
  using (var transaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      var employee = context.Employees.SqlQuery(
        "select top 1 * from Employee with (UPDLOCK) where EmpID = @id", id);
      // ...
      transaction.Commit(); 
    } 
    catch (Exception) 
    { 
      transaction.Rollback(); 
    } 
  } 
} 

Upvotes: 1

Related Questions