簡體   English   中英

從System.Data.Common.DbCommand繼承,Parameters屬性為null

[英]Inheriting from System.Data.Common.DbCommand, Parameters property is null

我正在忙於建立用於數據檢索和序列化的自定義框架,並且在定義專有數據庫連接/命令/參數組合時遇到了問題。 一切正常,直到我嘗試向自定義命令對象添加參數。 我有一個基類,使用通用函數來處理查詢的准備和執行,如下所示:

/// <summary>
/// Prepares a command for execution.
/// </summary>
/// <typeparam name="C">The type of command to prepare</typeparam>
/// <typeparam name="P">The type of parameters to add to the command</typeparam>
/// <param name="query">The query to be prepared for the command</param>
/// <param name="parameters">Dictionary of parameters to be added to the command</param>
/// <returns>A prepared command to execute against a database</returns>
protected virtual C Prepare<C, P>(string query, Dictionary<string, object> parameters)
    where C : DbCommand, new()
    where P : DbParameter, new()
{
    if (Connection == null)
        throw new System.Exception("Database connector hasn't been initialized yet. Call .Initialize() first.");
    C command = new C()
    {
        CommandText = query,
        Connection = Connection
    };
    if (parameters != null)
    {
        foreach (KeyValuePair<string, object> kvp in parameters)
        {
            command.Parameters.Add(new P() // <-- Breaks right here!
            {
                ParameterName = kvp.Key,
                Value = kvp.Value
            });
        }
        parameters = null;
    }
    return command;
}

我為大多數提供程序類型(Ole,ADO,ODBC,Oracle等)實現了類,但是它們基於System.Data命名空間中提供的標准.NET類型。 現在,我有一個完全自定義的類,該類繼承自要使用的System.Data.Common.DbCommand ,但是當我嘗試向上述新類中添加參數(在上面的Prepare函數中)時,我看到了新類的Parameters屬性類為null 它是從基類繼承的,並且設置為只讀,因此我無法自行對其進行初始化。 我的課程定義如下:

public sealed class Connection : System.Data.Common.DbConnection

我嘗試顯式覆蓋類中的屬性,作為public new List<Parameter> Parameters { get; set; } public new List<Parameter> Parameters { get; set; } public new List<Parameter> Parameters { get; set; }但無濟於事-通用函數仍使用基類的Parameters屬性。 獲取覆蓋屬性的句柄的唯一方法是將command (在Prepare函數中)顯式轉換為我的自定義類型,這顯然是我不想執行的操作。

我在這里想念什么嗎?

好的,我設法解決了這個問題。 真不敢相信我整個上午都對視盲! 在實現從System.Data.Common.DbCommand繼承的新類時,您必須重寫DbParameterCollection屬性。 急於創建新類,我只是在此屬性的getter中返回null ,並且我假設這就是Parameters屬性的用途。

因此,我剛剛實現了一個繼承自System.Data.Common.DbParameterCollection的新類,並在我的getter中返回了該類的新實例,它現在可以正常工作!

首先, new不會覆蓋該參數,而是將其隱藏。 這意味着使用DbCommand.Parameters的任何人都將看到原始實現,而使用您的類型的任何人都將看到您的實現。

只能使用override關鍵字來覆蓋屬性。 在這種情況下,您不能覆蓋Parameters因為它不是虛擬的。

其次, DbCommand.Parameters只是protected abstract DbCommand.DbCommandParameterCollection屬性上的外部接口。 您需要實現此方法以返回實際的參數集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM