2011-02-25 32 views
0

我只使用存儲過程對數據庫執行任何操作。我不希望使用ORB,你說在這之前:)ado.NET通過字段和表名從數據讀取器獲取字段

對於每個表我有一個相應的DAO類(VB或C#),例如:

Namespace Dao 

    Public Class Client 

     Public Sub New(ByVal id As Integer, ByVal description As String) 
      Me.id = id 
      Me.description = description 
     End Sub 

     Property id As Integer 
     Property description As String 
    End Class 

End Namespace 

的構造函數建立的類字段/屬性。 在另一類我通常建立我的DAO類的列表(容器),調用SELECT存儲過程,並獲得領域和建立單一的DAO:

Public Shared Function GetList() As List(Of Dao.Client) 

    Dim model As New List(Of Dao.Client) 

    Using dr As MySqlDataReader = DBUtils.CallReadingStoredProcedure("sp_get_clients") 

     While dr.Read 
      Dim client As New Dao.Client(dr.GetInt32(0), dr.GetString(1)) 
      model.Add(client) 
     End While 

     Return model 
    End Using 

End Function 

有時候,我需要創建相同Dao.class從另一種方法。如果構建它的字段很多,它將會很有用,而不是直接將值傳遞給DAO.class構造函數 - 這很容易出錯 - 只是將數據讀取器傳遞給不同的構造函數,從而提取字段並構建自身。

這就像通過建設責任到Dao.class本身:

Namespace Dao 

    Public Class Client 

     Public Sub New(ByVal dr As DataReader) 

      Me.id = dr.GetInt32("id") 
      Me.marca_id = dr.GetInt32("marca_id") 
      Me.categoria_id = dr.GetInt32("categoria_id") 
      Me.codice = dr.GetString("codice") 
      Me.descrizione = dr.GetString("descrizione") 
      ... many other 

     End Sub 
... 
    End Class 

End Namespace 

即使我使用不同的存儲過程來獲得客戶通過這種方式,我使用相同的代碼來構建它們。

只要datareader字段,即SELECT字段,它就會工作,總是命名爲始終命名爲。這是可能的,但是當我有一個JOIN,指定的域不包含表名,即該查詢在SP:

SELECT 
     OA.id,    -- 0 
     OA.articolo_id,   -- 1 
     OA.quantita,   -- 2 
     OA.quantita_evasa,  -- 3 
     OA.prezzo,   -- 4 
     A.id,    -- 5 
     A.marca_id,   -- 6 
     A.categoria_id,   -- 7 
     A.codice,   -- 8 
     A.descrizione,   -- 9 
     A.prezzo_listino,  -- 10 
     A.sconto,   -- 11 
     A.prezzo_speciale,  -- 12 
     A.ha_matricola,   -- 13 
     A.unita_misura,   -- 14 
     A.peso,    -- 15 
     A.codice_barre,   -- 16 
     other fields ... 
    FROM nm_ordini_articoli OA 
    JOIN articoli A ON (OA.articolo_id = A.id) 
    other JOINs... 

我不能這樣做,因爲dr.getInt32("OA.id")字段名稱是「ID 「和表名是」OA「。我可以使用索引,但這是純粹的瘋狂,因爲我應該嘗試在不同的存儲過程中使用相同的索引來存儲相同的數據!

問題是:我想要一個Dao構造函數來構建一個給予datareader的類;如何從數據讀取器獲取命名字段,包括表別名或名稱?我想要做類似dr.getInt32("real table name", "field name")dr.getInt32("table.field")

其他建議? 謝謝。

回答

0

我的一個聰明的朋友給了我這個優雅和簡單的解決方案:使用字段別名... 它工作該死的好!

SELECT 
     OA.id AS ordine_articolo_id, 
     ... 
2

查詢結果的大多數元數據可在DataReader.GetSchemaTable返回的DataTable中找到。該表的詳細信息與提供程序有關,對於SQL Server,它記錄在SqlDataReader.GetSchemaTable中,包括列ColumnName,BaseColumnNameBaseTableName

請記住,可能在查詢中計算了返回的列,但沒有給出名稱,因此它們都可以是null