生成强类型化数据集

如果给定符合 XML 架构定义语言 (XSD) 标准的 XML 架构,就可以使用随 Windows 软件开发工具包 (SDK) 提供的 XSD.exe 工具生成强类型 DataSet

(若要从数据库表创建 xsd,请参阅 WriteXmlSchema处理 Visual Studio 中的数据集)。

以下代码显示了使用此工具生成 数据集 的语法。

xsd.exe /d /l:CS XSDSchemaFileName.xsd /eld /n:XSDSchema.Namespace  

在此语法中,该 /d 指令指示工具生成 数据集,并 /l: 告知该工具使用哪种语言(例如 C# 或 Visual Basic .NET)。 可选 /eld 指令指定可以使用 LINQ to DataSet 查询生成的 数据集。 当同时指定此选项与 /d 选项时,将使用此选项。 有关详细信息,请参阅 查询类型化数据集。 可选/n:指令告知该工具还会为名为 XSDSchema.Namespace数据集生成命名空间。 命令的输出XSDSchemaFileName.cs,可在 ADO.NET 应用程序中编译和使用。 生成的代码可以编译为库或模块。

以下代码显示了使用 C# 编译器(csc.exe)将生成的代码编译为库的语法。

csc.exe /t:library XSDSchemaFileName.cs /r:System.dll /r:System.Data.dll  

/t: 指令指示工具编译到库,指令 /r: 指定编译所需的依赖库。 命令的输出是 XSDSchemaFileName.dll,使用指令编译 ADO.NET 应用程序 /r: 时,该命令可以传递给编译器。

以下代码演示了用于访问 ADO.NET 应用程序中传递给 XSD.exe 的命名空间的语法。

Imports XSDSchema.Namespace  
using XSDSchema.Namespace;  

下面的代码示例使用名为 CustomerDataSet 的类型化数据集Northwind 数据库加载客户列表。 使用 Fill 方法加载数据后,该示例将使用类型化的 CustomersRowDataRow) 对象循环访问 Customers 表中的每个客户。 这提供对 CustomerID 列的直接访问,而不是通过 DataColumnCollection 进行访问。

Dim customers As CustomerDataSet= New CustomerDataSet()  
Dim adapter As SqlDataAdapter New SqlDataAdapter( _  
  "SELECT * FROM dbo.Customers;", _  
  "Data Source=(local);Integrated " & _  
  "Security=SSPI;Initial Catalog=Northwind")  
  
adapter.Fill(customers, "Customers")  
  
Dim customerRow As CustomerDataSet.CustomersRow  
For Each customerRow In customers.Customers  
  Console.WriteLine(customerRow.CustomerID)  
Next  
CustomerDataSet customers = new CustomerDataSet();  
SqlDataAdapter adapter = new SqlDataAdapter(  
  "SELECT * FROM dbo.Customers;",  
  "Data Source=(local);Integrated " +  
  "Security=SSPI;Initial Catalog=Northwind");  
  
adapter.Fill(customers, "Customers");  
  
foreach(CustomerDataSet.CustomersRow customerRow in customers.Customers)  
  Console.WriteLine(customerRow.CustomerID);  

下面是用于示例的 XML 架构:

<?xml version="1.0" encoding="utf-8"?>  
<xs:schema id="CustomerDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">  
  <xs:element name="CustomerDataSet" msdata:IsDataSet="true">  
    <xs:complexType>  
      <xs:choice maxOccurs="unbounded">  
        <xs:element name="Customers">  
          <xs:complexType>  
            <xs:sequence>  
              <xs:element name="CustomerID" type="xs:string" minOccurs="0" />  
            </xs:sequence>  
          </xs:complexType>  
        </xs:element>  
      </xs:choice>  
    </xs:complexType>  
  </xs:element>  
</xs:schema>  

另请参阅