从事务中获取LAST_INSERT_ID

时间:2016-08-08 11:44:57

标签: asp.net-mvc asp.net-mvc-5 dapper

我有以下代码:

                using (MySqlConnection connection = new MySqlConnection(this.connectionString))
                {
                    connection.Open();
                    using (MySqlTransaction transaction = connection.BeginTransaction())
                    {
                        var r = connection.Execute(@"INSERT INTO tableA (`listId`, `parentListId`, `name`, `userId`)
                            VALUES
                            (NULL, @parentListId, @name, @userId);

                            INSERT INTO `tableA_misc` (`listId`, `userId`, `permissions`)
                            VALUES
                            (LAST_INSERT_ID(), @ownerId, 'Read');

                            SELECT CAST(LAST_INSERT_ID() AS UNSIGNED INTEGER);",
                        new {
                            parentListId = _parentListId,
                            name = _name,
                            userId = _currentUser.user_id
                        }, transaction);
                        transaction.Commit();
                    }
                }

如何检索the LAST_INSERT_ID(),因为r只返回插入的行数?

谢谢

1 个答案:

答案 0 :(得分:0)

将其更改为此修复:

 using (MySqlConnection connection = new MySqlConnection(this.connectionString))
                {
                    connection.Open();
                    using (MySqlTransaction transaction = connection.BeginTransaction())
                    {
                        var lastId = connection.Query<int>(@"INSERT INTO tableA (`listId`, `parentListId`, `name`, `userId`)
                            VALUES
                            (NULL, @parentListId, @name, @userId);

                            INSERT INTO `tableA_misc` (`listId`, `userId`, `permissions`)
                            VALUES
                            (LAST_INSERT_ID(), @ownerId, 'Read');

                            SELECT CAST(LAST_INSERT_ID() AS UNSIGNED INTEGER);",
                        new {
                            parentListId = _parentListId,
                            name = _name,
                            userId = _currentUser.user_id
                        }, transaction);
                        transaction.Commit();
                    }
            }