在架构中,可以使用键元素在元素或属性上指定 键 约束。 指定键约束的元素或属性在任何架构实例中必须具有唯一值,并且不能具有 null 值。
键约束类似于唯一约束,但定义键约束的列不能具有 null 值。
下表概述了可在键元素中指定的 msdata 属性。
属性名称 | DESCRIPTION |
---|---|
msdata:ConstraintName | 如果指定此属性,则其值将用作约束名称。 否则, name 属性提供约束名称的值。 |
msdata:PrimaryKey | 如果 PrimaryKey="true" 存在, IsPrimaryKey 约束属性设置为 true,因此使其成为主键。
AllowDBNull 列属性设置为 false,因为主键不能有 null 值。 |
在转换指定键约束的架构时,映射过程会在表上创建一个唯一约束,并将约束中每个列的 AllowDBNull 列属性设置为 false。 唯一约束的 IsPrimaryKey 属性也设置为 false,除非已在msdata:PrimaryKey="true"
元素上指定。 这与架构 PrimaryKey="true"
中的唯一约束相同。
在以下架构示例中, 密钥 元素指定 CustomerID 元素上的键约束。
<xs:schema id="cod"
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:string" 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="MyDataSet" msdata:IsDataSet="true">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element ref="Customers" />
</xs:choice>
</xs:complexType>
<xs:key msdata:PrimaryKey="true"
msdata:ConstraintName="KeyCustID"
name="KeyConstCustomerID" >
<xs:selector xpath=".//Customers" />
<xs:field xpath="CustomerID" />
</xs:key>
</xs:element>
</xs:schema>
键元素指定 Customers 元素的 CustomerID 子元素的值必须具有唯一值,并且不能具有 null 值。 在翻译 XML 架构定义语言 (XSD) 架构时,映射过程将创建下表:
Customers(CustomerID, CompanyName, Phone)
XML 架构映射还会在 CustomerID 列上创建 UniqueConstraint,如下所示DataSet。 (为简单起见,只显示相关属性。
DataSetName: MyDataSet
TableName: customers
ColumnName: CustomerID
AllowDBNull: False
Unique: True
ConstraintName: KeyCustID
Table: customers
Columns: CustomerID
IsPrimaryKey: True
在生成的数据集中,UniqueConstraint 的 IsPrimaryKey 属性设置为 true,因为架构在msdata:PrimaryKey="true"
元素中指定。
DataSet 中 UniqueConstraint 的 ConstraintName 属性的值是架构中键元素中指定的 msdata:ConstraintName 属性的值。