带有Custom CommandTimeout的WebMatrix Database.Query

时间:2014-10-20 17:45:52

标签: c# sql-server webmatrix sqldatareader command-timeout

使用TestTable和Procedure

考虑以下TestDb
USE TestDb
GO
--DROP TABLE dbo.TestTable
IF NOT EXISTS (SELECT 1 FROM sys.tables WHERE name = 'TestTable')
BEGIN
    CREATE TABLE dbo.TestTable
    (
        RecordId int NOT NULL IDENTITY(1,1) PRIMARY KEY
        , StringValue varchar(50) NULL
        , DateValue date NULL
        , DateTimeValue datetime NULL
        , MoneyValue money NULL
        , DecimalValue decimal(19,4) NULL
        , IntValue int NULL
        , BitValue bit NOT NULL
    )

    INSERT INTO dbo.TestTable
    SELECT 'Test', CAST(GETDATE() AS DATE), GETDATE(), 100.15, 100.0015, 100, 1
    UNION SELECT NULL, NULL, NULL, NULL, NULL, NULL, 0
END
GO
IF EXISTS (SELECT 1 FROM sys.procedures WHERE name = 'Get_TestTable')
    DROP PROCEDURE dbo.Get_TestTable
GO
CREATE PROCEDURE dbo.Get_TestTable (@RecordId int = NULL) AS WAITFOR DELAY '00:00:30'; SELECT * FROM dbo.TestTable WHERE RecordId = ISNULL(@RecordId,RecordId);
GO
EXEC dbo.Get_TestTable @RecordId = NULL

使用WebMatrix内置数据库查询助手时,您可以执行以下操作:

@{
    string errorMessage = String.Empty;
    int? RecordId = null;
    IEnumerable<dynamic> rowsTestTable = null;

    try
    {
        using (Database db = Database.Open("TestDb"))
        {
            rowsTestTable = db.Query("EXEC dbo.Get_TestTable @RecordId=@0",RecordId);
        }
    }
    catch (Exception ex)
    {
        errorMessage = ex.Message;
    }
}
<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @if(errorMessage == String.Empty)
        {
            <table border="1">
                <thead>
                    <tr>
                        <th>RecordId</th>
                        <th>StringValue</th>
                        <th>DateValue</th>
                        <th>DateTimeValue</th>
                        <th>MoneyValue</th>
                        <th>DecimalValue</th>
                        <th>IntValue</th>
                        <th>BitValue</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach(var row in rowsTestTable)
                    {
                        <tr>
                            <td>@row["RecordId"]</td>
                            <td>@row["StringValue"]</td>
                            <td>@if(@row["DateValue"] != null){@Html.Raw(String.Format("{0:MM/dd/yyyy}",@row["DateValue"]));}</td>
                            <td>@if(@row["DateTimeValue"] != null){@Html.Raw(String.Format("{0:MM/dd/yyyy hh:mm:ss.fff tt}",@row["DateTimeValue"]));}</td>
                            <td>@if(@row["MoneyValue"] != null){@Html.Raw(String.Format("{0:c}",@row["MoneyValue"]));}</td>
                            <td>@row["DecimalValue"]</td>
                            <td>@row["IntValue"]</td>
                            <td>@row["BitValue"]</td>
                        </tr>
                    }
                </tbody>
            </table>
        }
        <p>@errorMessage</p>

        <h4>No Additional Problem - On handling of DateValue</h4>
        @try
        {
            foreach(var row in rowsTestTable)
            {
                <p>@if(row.DateValue != null){@Html.Raw(DateTime.Parse(row.DateValue.ToString()))}</p>
            }
        }
        catch (Exception ex)
        {
            <p>@ex.Message</p>
        }

        <h4>No Additional Problem - On handling of MoneyValue (and other number values)</h4>
        @try
        {
            foreach(var row in rowsTestTable)
            {
                <p>@if(row.MoneyValue != null){@Html.Raw(Double.Parse(row.MoneyValue.ToString()))}</p>
            }
        }
        catch (Exception ex)
        {
            <p>@ex.Message</p>
        }
    </body>
</html>

这会导致Timeout过期错误,因为WebMatrix Database.Query帮助程序已修复默认的30秒CommandTimeout。 有没有办法将单个查询的默认值覆盖为5分钟?

没有找到解决方案,我开始创建自己的SimpleQuery助手,基于大量的搜索和尝试,直到我最终找到一个我能够理解和适应的code reference

using System.Collections.Generic; // IEnumerable<dynamic>
using System.Data; // IDataRecord
using System.Data.SqlClient; // SqlConnection
using System.Dynamic; // DynamicObject

public class SimpleQuery
{
    public static IEnumerable<dynamic> Execute(string connectionString, string commandString, int commandTimeout)
    {
        using (var connection = new SqlConnection(connectionString))
        {
            using (var command = new SqlCommand(commandString, connection))
            {
                command.CommandTimeout = commandTimeout;
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    foreach (IDataRecord record in reader)
                    {
                        yield return new DataRecordDynamicWrapper(record);
                    }
                }
                connection.Close();
            }
        }
    }

    public class DataRecordDynamicWrapper : DynamicObject
    {
        private IDataRecord _dataRecord;
        public DataRecordDynamicWrapper(IDataRecord dataRecord) { _dataRecord = dataRecord; }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = _dataRecord[binder.Name];
            return result != null;
        }
    }
}

所以现在通过对Web代码的更改来使用新的SimpleQuery帮助器,我可以得到几乎相同的结果,但有一些问题

@{
    string errorMessage = String.Empty;
    int? RecordId = null;
    IEnumerable<dynamic> rowsTestTable = null;

    try
    {
        string commandString = String.Format("dbo.Get_TestTable @RecordId={0}", RecordId == null ? "null" : RecordId.ToString()); // Problem 1: Have to use String.Format to embed the Parameters
        rowsTestTable = SimpleQuery.Execute(System.Configuration.ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString,commandString,300);
        foreach(var row in rowsTestTable) { break; } // Problem 2: Have to force query execution here, so the error (if any) gets trapped here
    }
    catch (Exception ex)
    {
        errorMessage = ex.Message;
    }
}
<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @if(errorMessage == String.Empty)
        {
            <table border="1">
                <thead>
                    <tr>
                        <th>RecordId</th>
                        <th>StringValue</th>
                        <th>DateValue</th>
                        <th>DateTimeValue</th>
                        <th>MoneyValue</th>
                        <th>DecimalValue</th>
                        <th>IntValue</th>
                        <th>BitValue</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach(var row in rowsTestTable)
                    {
                        <tr>
                            @*<td>@row["RecordId"]</td>*@  <!-- Problem 3: Can't reference as row["FieldName"], so if any field names have spaces or other special characters, can't reference -->
                            <td>@row.RecordId</td>
                            <td>@row.StringValue</td>
                            <td>@if(@row.DateValue != null){@Html.Raw(String.Format("{0:MM/dd/yyyy}",@row.DateValue));}</td>
                            <td>@if(@row.DateTimeValue != null){@Html.Raw(String.Format("{0:MM/dd/yyyy hh:mm:ss.fff tt}",@row.DateTimeValue));}</td>
                            <td>@if(@row.MoneyValue != null){@Html.Raw(String.Format("{0:c}",@row.MoneyValue));}</td>
                            <td>@row.DecimalValue</td>
                            <td>@row.IntValue</td>
                            <td>@row.BitValue</td>
                        </tr>
                    }
                </tbody>
            </table>
        }
        <p>@errorMessage</p>

        <h4>Additional Problem - Unexpected handling of DateValue</h4>
        @try
        {
            foreach(var row in rowsTestTable)
            {
                <p>@if(row.DateValue != null){@Html.Raw(DateTime.Parse(row.DateValue.ToString()))}</p>
            }
        }
        catch (Exception ex)
        {
            <p>@ex.Message</p>
        }

        <h4>Additional Problem - Unexpected handling of MoneyValue (and other number values)</h4>
        @try
        {
            foreach(var row in rowsTestTable)
            {
                <p>@if(row.MoneyValue != null){@Html.Raw(Double.Parse(row.MoneyValue.ToString()))}</p>
            }
        }
        catch (Exception ex)
        {
            <p>@ex.Message</p>
        }
    </body>
</html>

问题1-3在使用SimpleQuery帮助程序的第二个Web代码中进行了注释。这些我可以解决,但我仍然在努力解决为什么没有检测到数字和日期值的NULL检查。

我很感激帮助正确检测那些,所以我可以避免使用Double.Parse或DateTime.Parse时的后续错误。我还要感谢SimpleQuery帮助程序或您看到的任何其他内容的任何一般指针/改进。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以尝试切换到使用Dapper。它具有与WebMatrix.Data非常相似的语法,可以返回结果IEnumerable<dynamic>或强类型(如果您愿意),并允许您基于每个查询覆盖命令超时。

https://github.com/StackExchange/dapper-dot-net

答案 1 :(得分:0)

使用我的SimpleQuery Helper时使用以下代码可以检测Null或String.Empty,因为转换为ToString()时来自我的Helper的值在来自Database.Query时作为String.Empty出现,它们返回为NULL

@try
{
    foreach(var row in rowsTestTable)
    {
        <p>@if(!String.IsNullOrEmpty(row.DateValue.ToString())){@Html.Raw(DateTime.Parse(row.DateValue.ToString()))}</p>
    }
}
catch (Exception ex)
{
    <p>@ex.Message</p>
}

虽然这并没有向我解释为什么存在差异或者如何使我的SimpleQuery Helper更像是Database.Query,但它确实帮助我解决了当前的问题。