为什么存储过程可以工作,但命令会引发超时?

Why does the stored procedure work, but command throws timeout?

提问人:Gabriel Scarafia 提问时间:10/25/2023 最后编辑:marc_sGabriel Scarafia 更新时间:10/25/2023 访问量:66

问:

这是我的函数,应该插入一行(对不起我的英语不好):addDocumentint,guid,string

internal static bool AddDocument(int userId, IFormFile document)
{
    using SqlCommand cmd = new() { CommandType = CommandType.StoredProcedure };
    cmd.BeginTransaction(IsolationLevel.ReadUncommitted);

    try
    {
        cmd.Parameters.Clear();
        cmd.CommandText = "UserDocument_Add";

        cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = userId;
        cmd.Parameters.Add("@FileName", SqlDbType.NVarChar, 200).Value = document.FileName;

        var guid = Guid.NewGuid();
        cmd.Parameters.Add("@Guid", SqlDbType.UniqueIdentifier).Value = guid;

        // This line throws a timeout error
        var result = cmd.ExecuteReturnInt32(); 

        // <--more code-->

        return true;
    }
    catch
    {
        cmd.Rollback();
        return false;
    }
}

这是我在 SQL Server 中创建的存储过程:

CREATE PROCEDURE [dbo].[UserDocument_Add]
    @UserId int,
    @FileName nvarchar(200),
    @Guid uniqueidentifier
AS
BEGIN
    SET NOCOUNT ON;

    IF EXISTS (SELECT 1 FROM [User_Document] 
               WHERE (([UserId] = @UserId) AND (ExternalId = @Guid)))
    BEGIN
        RETURN -1;
    END

    INSERT INTO [User_Document] ([UserId], ExternalId, [FileName], CreatedBy)
    VALUES (@UserId, @Guid, @FileName, @UserId)

    RETURN 1
END
C# SQL SQL 服务器 存储过程 后端

评论

1赞 jmcilhinney 10/25/2023
是连接超时还是命令超时?这些方法从何而来?他们看起来不像 的标准成员。至少,当我搜索文档时,它们不会出现。我根本没有看到与那里有任何关联。BeginTransactionExecuteReturnInt32SqlCommandSqlConnection
0赞 Gabriel Scarafia 10/25/2023
嗨,错误是“Microsoft.Data.SqlClient.SqlException HResult=0x80131904 Message=Execution Timeout Expired” 我正在使用一个扩展的库,这是一个执行(我知道不是错误的一部分,因为它在应用程序的其他部分工作)只是一个转换 int32 (它也不应该是错误的一部分,因为它在应用程序的其他部分工作)SqlConnectionBeginTransactionSqlConnectionExecuteReturnInt32()ExecuteNonQuery()
0赞 jmcilhinney 10/25/2023
您需要提供所有相关信息。我们不应该对我们对工作一无所知的方法做出假设。至于问题,抛出超时异常需要多长时间?默认命令超时为 30 秒。这是在调用抛出该异常后需要等待多长时间吗?ExecuteReturnInt32
0赞 AlwaysLearning 10/25/2023
旁白。。。实际上应该根据 和 检查重复项吗?根据显示的内容,它极不可能并且永远不会重复,因为本质上是一个大随机数。UserDocument_Add@UserId@FileName@UserId@Guid@Guid
0赞 Zohar Peled 10/25/2023
注意:存储过程在多线程环境中并不安全,因为从理论上讲,select 和 insert 语句之间可能存在插入或更新查询。为了确保此过程的安全,您需要锁定表。这是一个更好的选择。

答: 暂无答案