如何在Entity Framework中获取SQL Server序列的下一个值?

我想在Entity Framework中使用SQL Server sequence对象来显示数字序列,然后将其保存到数据库中。

在当前场景中,我正在通过存储过程中的一个增量(存储在一个表中的先前值)并将该值传递给C#代码来执行相关操作。

为了实现这一点,我需要一个表,但现在我想将它转换为一个sequence对象(它会带来什么优势?)。

我知道如何在SQL Server中创建序列并获取下一个值。

但我想知道如何在Entity Framework中获取SQL Server的sequence对象的下一个值?

我无法在SO中的相关问题中找到有用的答案。

提前致谢。

您可以在SQL Server中创建一个简单的存储过程,选择下一个序列值,如下所示:

 CREATE PROCEDURE dbo.GetNextSequenceValue AS BEGIN SELECT NEXT VALUE FOR dbo.TestSequence; END 

然后,您可以将该存储过程导入到Entity Framework中的EDMX模型中,并调用该存储过程并获取序列值,如下所示:

 // get your EF context using (YourEfContext ctx = new YourEfContext()) { // call the stored procedure function import var results = ctx.GetNextSequenceValue(); // from the results, get the first/single value int? nextSequenceValue = results.Single(); // display the value, or use it whichever way you need it Console.WriteLine("Next sequence value is: {0}", nextSequenceValue.Value); } 

更新:实际上,您可以跳过存储过程并从EF上下文中运行此原始SQL查询:

 public partial class YourEfContext : DbContext { .... (other EF stuff) ...... // get your EF context public int GetNextSequenceValue() { var rawQuery = Database.SqlQuery("SELECT NEXT VALUE FOR dbo.TestSequence;"); var task = rawQuery.SingleAsync(); int nextVal = task.Result; return nextVal; } } 

由于我使用Code First而且我不想要一些额外的DDL,这是我的方式:(EF Core 2.1,SQL Server)

定义顺序:

 protected override void OnModelCreating( ModelBuilder modelBuilder ) { modelBuilder.HasSequence("MySequence"); } 

为了检索它,我将以下函数添加到上下文中:

 public int GetMySequence() { SqlParameter result = new SqlParameter("@result", System.Data.SqlDbType.Int) { Direction = System.Data.ParameterDirection.Output }; Database.ExecuteSqlCommand( "SELECT @result = (NEXT VALUE FOR MySequence)", result); return (int)result.Value; } 

如果你想在存储过程之外做,你可以创建一个只包含字符串或int的实体类(无论你的序列返回什么),然后对它运行一些原始SQL。 然后只需使用您想要的对象或字符串。

  SEQ_TXN_ID txn_id= _context.SEQ_TXN_IDs.SqlQuery("SELECT txn_id_seq.NEXTVAL txn_ID FROM DUAL").FirstOrDefault();