技术开发 频道

ASP.NET 2.0中DataTable小兵变大将

  【IT168 技术文档】

  先看一段Web Service的代码:

[WebMethod] public DataTable GetInfo() ...{ OleDbConnection nwindConn = new OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=D:\\Northwind\\northwind.mdb;"); OleDbCommand selectCMD = new OleDbCommand("SELECT CustomerID, CompanyName FROM Customers" , nwindConn); selectCMD.CommandTimeout = 30; OleDbDataAdapter custDA = new OleDbDataAdapter(); custDA.SelectCommand = selectCMD; DataSet custDS = new DataSet(); custDA.Fill(custDS, "Customers"); return custDS.Tables[0]; }
  
  在.NET 1.1 中,这是典型的一个错误,在.NET 1.0 、1.1中,WEB Service 的返回或者输入参数不能是DataTable,这是一个众人皆知的知识点。原因就是DataTable不象DataSet那样支持序列化。在.NET 1.1中,我们解决这个问题的方法就是使用DataSet。但是使用DataSet 的时候,经常会有一种杀鸡用牛刀的感觉。
 
  .NET 1.1 中使用DataTable作为WEB Service 返回值会报以下异常:
 
  类型 System.ComponentModel.ISite 的成员 System.ComponentModel.MarshalByValueComponent.Site 是接口,因此无法将其序列化。
 
  在.NET 2.0 中,以上同样的代码,则没有任何问题了。原因是2.0中DataTable实现了序列化、反序列。
 
  在VS2005 Beta2 的文档中,我们可以看到2.0中DataTable实现了以下接口:
 
  Explicit Interface Implementations
  System.ComponentModel.IListSource.get_ContainsListCollection
  System.ComponentModel.IListSource.GetList
  System.XML.Serialization.IXMLSerializable.GetSchema
  System.Xml.Serialization.IXmlSerializable.ReadXml
  System.Xml.Serialization.IXmlSerializable.WriteXml 
 
  而在1.1中,DataTable 只实现了一个接口:
 
  Explicit Interface Implementations
  System.ComponentModel.IListSource.ContainsListCollection 
 
  把DataSet中的一些功能移到 DataTable中,2.0中还有 Merge 方法,即合并数个数据集。
 
  DataTable的代码合并参看下面代码:
private static void DemonstrateMergeTable() ...{ DataTable table1 = new DataTable("Items"); DataColumn column1 = new DataColumn("id", typeof(System.Int32)); DataColumn column2 = new DataColumn("item", typeof(System.Int32)); table1.Columns.Add(column1); table1.Columns.Add(column2); table1.PrimaryKey = new DataColumn[] ...{ column1 }; table1.RowChanged += new System.Data.DataRowChangeEventHandler(Row_Changed); DataRow row; for (int i = 0; i <= 3; i++) ...{ row = table1.NewRow(); row["id"] = i; row["item"] = i; table1.Rows.Add(row); } // Accept changes. table1.AcceptChanges(); DataTable table2 = table1.Clone(); row = table2.NewRow(); row["id"] = 14; row["item"] = 774; table2.Rows.Add(row); row = table2.NewRow(); row["id"] = 12; row["item"] = 555; table2.Rows.Add(row); row = table2.NewRow(); row["id"] = 13; row["item"] = 665; table2.Rows.Add(row); // Merge table2 into the table1. table1.Merge(table2); }

  综合上述,.NET 2.0 中 DataTable 从后台的默默无问的小兵变成独当一面的大将了。

 

0
相关文章