为什么.NET SQL UPDATE只工作一次?

时间:2019-05-04 20:08:20

标签: c# .net sql-server tsql

由于某种原因,下面的代码实际上仅在触发后运行一次(如果幸运的话,有时会运行两次)。

此后,它返回res > 0,但数据库中的行未更改。任何想法为什么会发生这种情况以及如何解决?

我已经尝试处置DbCommand对象(如您所见)。

public static async Task<bool> SetWallpaper(CornUser User, ulong ID)
{
    using (DbCommand dbCommand = DbProviderFactory.CreateCommand()) 
    { 
        dbCommand.Connection = SQLConnection;

        dbCommand.CommandText = @"
            UPDATE Users
            SET Wallpaper = @Wallpaper
            WHERE DiscordID = @DISCORDID";

        dbCommand.Parameters.Add(new SqlParameter("@DISCORDID", System.Data.SqlDbType.BigInt) { Value = User.ID });
        dbCommand.Parameters.Add(new SqlParameter("@Wallpaper", System.Data.SqlDbType.Int) { Value = ID });

        dbCommand.Prepare();

        int res = await dbCommand.ExecuteNonQueryAsync();
        return (res > 0);
    }
}

我希望它实际上将Wallpaper列始终更改为ID

1 个答案:

答案 0 :(得分:1)

好...我找到了解决方案。

因此,经过几天的修补,我完全费心地重写了整个UserDataService类(包含此类Tasks。

并将命令更改为以下内容:

using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            using (DbConnection connection = DbProviderFactory.CreateConnection())
            {
                connection.ConnectionString = SQLConnectionString;
                await connection.OpenAsync();
                DbCommand command = connection.CreateCommand();
                command.CommandText = "UPDATE Users SET Wallpaper=@WallpaperID WHERE DiscordID=@DiscordID";
                command.Parameters.Add(new SqlParameter("@DiscordID", SqlDbType.BigInt) { Value = UserID });
                command.Parameters.Add(new SqlParameter("@WallpaperID", SqlDbType.BigInt) { Value = WallpaperID });
                await command.ExecuteNonQueryAsync();
                scope.Complete();
                return true;
            }
        }

似乎可以做到这一点!

感谢@RazvanSocol引领我朝着正确的方向前进!