如何获得SQL Server的序列的下一个值在实体框架? [英] How to get next value of SQL Server sequence in Entity Framework?
问题描述
我想利用SQL Server的 序
对象实体框架中显示数字序列之前将其保存到数据库中。
I want to make use SQL Server sequence
objects in Entity Framework to show number sequence before save it into database.
在当前情况下,我在做一个存储过程(前值存储在一个表)由增量相关的东西,并通过该值的C#代码。
In current scenario I'm doing something related by increment by one in stored procedure (previous value stored in one table) and passing that value to C# code.
要实现这一目标,我需要一个表,但现在我想将其转换为序
对象(它会给什么优势?)。
To achieve this I needed one table but now I want to convert it to a sequence
object (will it give any advantage ?).
我知道如何创建序列,并获得在SQL Server下一个值。
I know how to create sequence and get next value in SQL Server.
但我想知道如何获得实体框架序列的下一个值的SQL Server
对象吗?
But I want to know how to get next value of sequence
object of SQL Server in Entity Framework?
我是无法找到的相关问题在SO。
I am to unable to find useful answers in Related questions in SO.
在此先感谢。
推荐答案
您可以创建一个简单的存储程序中的SQL Server,它选择这样的一个序列值:
You can create a simple stored procedure in SQL Server that selects the next sequence value like this:
CREATE PROCEDURE dbo.GetNextSequenceValue
AS
BEGIN
SELECT NEXT VALUE FOR dbo.TestSequence;
END
然后可以导入存储过程到实体框架的EDMX模型,并调用存储过程并获取这样的序列:
and then you can import that stored procedure into your EDMX model in Entity Framework, and call that stored procedure and fetch the sequence value like this:
// 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查询:
Update: actually, you can skip the stored procedure and just run this raw SQL query from your EF context:
public partial class YourEfContext : DbContext
{
.... (other EF stuff) ......
// get your EF context
public int GetNextSequenceValue()
{
var rawQuery = Database.SqlQuery<int>("SELECT NEXT VALUE FOR dbo.TestSequence;");
var task = rawQuery.SingleAsync();
int nextVal = task.Result;
return nextVal;
}
}
这篇关于如何获得SQL Server的序列的下一个值在实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!