How do I perform an insert and return inserted identity with Dapper?

后端 未结 8 830
忘掉有多难
忘掉有多难 2020-11-28 01:45

How do I perform an insert to database and return inserted identity with Dapper?

I\'ve tried something like this:

string sql = \"DECLARE @ID int; \"          


        
相关标签:
8条回答
  • 2020-11-28 01:52

    It does support input/output parameters (including RETURN value) if you use DynamicParameters, but in this case the simpler option is simply:

    var id = connection.QuerySingle<int>( @"
    INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
    SELECT CAST(SCOPE_IDENTITY() as int)", new { Stuff = mystuff});
    

    Note that on more recent versions of SQL Server you can use the OUTPUT clause:

    var id = connection.QuerySingle<int>( @"
    INSERT INTO [MyTable] ([Stuff])
    OUTPUT INSERTED.Id
    VALUES (@Stuff);", new { Stuff = mystuff});
    
    0 讨论(0)
  • 2020-11-28 01:53

    KB:2019779,"You may receive incorrect values when using SCOPE_IDENTITY() and @@IDENTITY", The OUTPUT clause is the safest mechanism:

    string sql = @"
    DECLARE @InsertedRows AS TABLE (Id int);
    INSERT INTO [MyTable] ([Stuff]) OUTPUT Inserted.Id INTO @InsertedRows
    VALUES (@Stuff);
    SELECT Id FROM @InsertedRows";
    
    var id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();
    
    0 讨论(0)
  • 2020-11-28 01:56

    Not sure if it was because I'm working against SQL 2000 or not but I had to do this to get it to work.

    string sql = "DECLARE @ID int; " +
                 "INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff); " +
                 "SET @ID = SCOPE_IDENTITY(); " +
                 "SELECT @ID";
    
    var id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();
    
    0 讨论(0)
  • 2020-11-28 02:00

    The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).

    You can return it as an int by casting it as follows:

    string sql = @"
    INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
    SELECT CAST(SCOPE_IDENTITY() AS INT)";
    
    int id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();
    
    0 讨论(0)
  • 2020-11-28 02:03

    I see answer for sql server, well here it is for MySql using a transaction

    
        Dim sql As String = "INSERT INTO Empleado (nombres, apepaterno, apematerno, direccion, colonia, cp, municipio, estado, tel, cel, correo, idrol, relojchecadorid, relojchecadorid2, `activo`,`extras`,`rfc`,`nss`,`curp`,`imagen`,sueldoXHra, IMSSCotiza, thumb) VALUES (@nombres, @apepaterno, @apematerno, @direccion, @colonia, @cp, @municipio, @estado, @tel, @cel, @correo, @idrol, @relojchecadorid, @relojchecadorid2, @activo, @extras, @rfc, @nss, @curp, @imagen,@sueldoXHra,@IMSSCotiza, @thumb)"
        
                Using connection As IDbConnection = New MySqlConnection(getConnectionString())
                    connection.Open()
                    Using transaction = connection.BeginTransaction
                        Dim res = connection.Execute(sql, New With {reg.nombres, reg.apepaterno, reg.apematerno, reg.direccion, reg.colonia, reg.cp, reg.municipio, reg.estado, reg.tel, reg.cel, reg.correo, reg.idrol, reg.relojchecadorid, reg.relojchecadorid2, reg.activo, reg.extras, reg.rfc, reg.nss, reg.curp, reg.imagen, reg.thumb, reg.sueldoXHra, reg.IMSSCotiza}, commandTimeout:=180, transaction:=transaction)
                        lastInsertedId = connection.ExecuteScalar("SELECT LAST_INSERT_ID();", transaction:=transaction)
                        If res > 0 Then 
    transaction.Commit()
    return true
    end if
                        
                    End Using
                End Using
    
    0 讨论(0)
  • 2020-11-28 02:04

    There is a great library to make your life easier Dapper.Contrib.Extensions. After including this you can just write:

    public int Add(Transaction transaction)
    {
            using (IDbConnection db = Connection)
            {
                    return (int)db.Insert(transaction);
            }
    }
    
    0 讨论(0)
提交回复
热议问题