sql >> Base de Datos >  >> RDS >> Sqlserver

¿Cómo obtener el siguiente valor de la secuencia de SQL Server en Entity Framework?

Puede crear un procedimiento almacenado simple en SQL Server que seleccione el siguiente valor de secuencia como este:

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

y luego puede importar ese procedimiento almacenado en su modelo EDMX en Entity Framework, llamar a ese procedimiento almacenado y obtener el valor de la secuencia de esta manera:

// 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);
}

Actualización: en realidad, puede omitir el procedimiento almacenado y simplemente ejecutar esta consulta SQL sin procesar desde su contexto EF:

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;
    }
}