在 XML 架构定义语言 (XSD) 架构中, 唯 一元素指定元素或属性的唯一性约束。 在将 XML 架构转换为关系架构的过程中,对 XML 架构中的元素或属性指定的唯一约束将映射到生成的相应DataTable元素或属性中的DataSet唯一约束。
下表概述了可以在unique 元素中指定的 msdata 属性。
属性名称 | DESCRIPTION |
---|---|
msdata:ConstraintName | 如果指定此属性,则其值将用作约束名称。 否则, name 属性提供约束名称的值。 |
msdata:PrimaryKey | 如果PrimaryKey="true" 存在于唯一元素中,则使用IsPrimaryKey属性设置为true来创建唯一约束。 |
下面的示例演示一个 XML 架构,该架构使用 唯 一元素来指定唯一性约束。
<xs:schema id="SampleDataSet"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="Customers">
<xs:complexType>
<xs:sequence>
<xs:element name="CustomerID" type="xs:integer"
minOccurs="0"/>
<xs:element name="CompanyName" type="xs:string"
minOccurs="0"/>
<xs:element name="Phone" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="SampleDataSet" msdata:IsDataSet="true">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element ref="Customers" />
</xs:choice>
</xs:complexType>
<xs:unique msdata:ConstraintName="UCustID" name="UniqueCustIDConstr" > <xs:selector xpath=".//Customers" /> <xs:field xpath="CustomerID" /> </xs:unique>
</xs:element>
</xs:schema>
架构中的 唯 一元素指定,对于文档实例中的所有 Customers 元素, CustomerID 子元素的值必须是唯一的。 在生成 DataSet 时,映射过程读取此架构并生成下表:
Customers (CustomerID, CompanyName, Phone)
映射过程还会对 CustomerID 列创建唯一约束,如以下 数据集所示。 (为简单起见,只显示相关属性。
DataSetName: MyDataSet
TableName: Customers
ColumnName: CustomerID
AllowDBNull: True
Unique: True
ConstraintName: UcustID Type: UniqueConstraint
Table: Customers
Columns: CustomerID
IsPrimaryKey: False
在生成的 数据集 中, IsPrimaryKey 属性对于唯一约束设置为 False 。 在该列上设置的 唯一属性表明CustomerID 列的值必须是唯一的(但它们可以为空引用,这由该列的 AllowDBNull 属性指定)。
如果修改架构并将可选的 msdata:PrimaryKey 属性值设置为 True,则会对表创建唯一约束。 AllowDBNull 列属性设置为 False,约束的 IsPrimaryKey 属性设置为 True,从而使 CustomerID 列成为主键列。
可以对 XML 架构中的元素或属性的组合指定唯一约束。 以下示例演示如何通过在架构中添加另一个 xs:field 元素,指定在任何实例中,所有 Customers 的 CustomerID 和 CompanyName 值组合必须是唯一的。
<xs:unique
msdata:ConstraintName="SomeName"
name="UniqueCustIDConstr" >
<xs:selector xpath=".//Customers" />
<xs:field xpath="CustomerID" />
<xs:field xpath="CompanyName" />
</xs:unique>
这是在生成的 数据集中创建的约束。
ConstraintName: SomeName
Table: Customers
Columns: CustomerID CompanyName
IsPrimaryKey: False