【问题标题】:SQL to Entity FrameworkSQL 到实体框架
【发布时间】:2023-03-07 11:16:01
【问题描述】:
我正在使用 Azure SQL 数据库和实体框架对其执行数据库操作。
如何将此 SQL 查询转换为实体框架?
begin tran set transaction isolation level serializable
go
select top 1 * from Employee with (UPDLOCK) where EmpID = @id;
......
commit
当某个线程正在读取一行并对其执行某些操作时,我想从其他线程中锁定一行。
我无法使用存储过程,因为我正在使用 Azure SQL 数据库。
【问题讨论】:
标签:
entity-framework
azure
azure-sql-database
【解决方案1】:
我不知道您为什么不能为此使用存储过程。正如 marc_s 提到的 Azure SQL DB 支持存储过程。也就是说,如果需要,您可以随时从 EF 执行查询。 EF 不支持为 LINQ 查询指定查询提示,因此最简单的方法是使用原始 SQL 执行 API。使用 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();
}
}
}