2012-08-07 70 views
0

我正在開發使用MVC 3的Web應用程序。此應用程序通過ASMX Web服務連接到SQL Server數據庫。每個Web方法調用一個存儲過程並返回一個DataTable。ASMX Web服務,存儲過程和MVC模型

這是我用來調用存儲過程的代碼:

public static DataTable ExecSP(string StoredProcedureName, List<string> ParameterNames, List<Object> ParameterValues) 
    { 
     SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString); 
     SqlDataReader Reader = null; 
     DataTable SPResult = null; 

     try 
     { 
      Connection.Open(); 
      SqlCommand Command = new SqlCommand("dbo." + StoredProcedureName, Connection); 
      Command.CommandType = CommandType.StoredProcedure; 

      if (ParameterNames != null) 
      { 
       for (int i = 0; i < ParameterNames.Count; i++) 
       { 
        SqlParameter Parameter = new SqlParameter(ParameterNames[i], ParameterValues[i]); 
        if (Parameter.SqlDbType.Equals(SqlDbType.NVarChar)) 
        { 
         Parameter.SqlDbType = SqlDbType.VarChar; 
        } 

        if (Parameter.SqlValue == null) 
        { 
         Parameter.SqlValue = DBNull.Value; 
        } 

        Command.Parameters.Add(Parameter); 
       } 
      } 
      Reader = Command.ExecuteReader(); 
      SPResult = new DataTable(); 
      SPResult.Load(Reader); 

     } 
     catch (Exception ex) 
     { 
      throw; 
     } 
     finally 
     { 
      Connection.Close(); 

      if (Reader != null) 
      { 
       Reader.Close(); 
      } 
     } 
     return SPResult; 
    } 

我想知道是否有這個數據錶轉換成則可以傳遞一個型號一個直接的方式到一個視圖(例如,像在AJAX文章中發生的模型綁定),如果沒有,有什麼選擇。我知道使用LINQ可能會解決這個問題,但我無法使用它。

在此先感謝。

此致敬禮。

回答

0

找到了解決方案。

我建立了一個翻譯的任何DataTable到我指定的任何類的List的一般方法:

public static List<T> Translate<T>(DataTable SPResult, Func<object[],T> del) 
    { 
     List<T> GenericList = new List<T>(); 

     foreach (DataRow Row in SPResult.Rows) 
     { 
      GenericList.Add(del(Row.ItemArray)); 
     } 

     return GenericList; 
    } 

其中del是一個代表。當調用這個方法時,del應該是指定類的構造函數。於是,在所有模型類,我建立了接收object[] RowFromTable

public class MyClass 
{ 
    public int ID { get; set; } 
    public string Description { get; set; } 

    public FormaProcesso(object[] RowFromTable) 
    { 
     this.ID = (int)RowFromTable[0]; 
     this.Description = RowFromTable[1].ToString(); 
    } 
} 

最後,把它放在一起構造,這是當我調用Web方法會發生什麼:

public List<MyClass> GetAll() 
    { 

     DataTable SPResult = MyWebService.GetAll().Table; 

     return Translate<MyClass>(SPResult, l => new MyClass(l)); 

    } 

得到了來自here的想法