将主要的 XML 架构 (XSD) 约束映射到数据集约束

在架构中,可以使用元素或属性 key 指定键约束。 指定键约束的元素或属性在任何架构实例中必须具有唯一值,并且不能具有 null 值。

键约束类似于唯一约束,但定义键约束的列不能具有 null 值。

下表概述了您可以在 key 元素中指定的 msdata 属性。

属性名称 DESCRIPTION
msdata:ConstraintName 如果指定此属性,则其值将用作约束名称。 否则,该 name 特性提供约束名称的值。
msdata:PrimaryKey 如果 PrimaryKey="true" 存在,则 IsPrimaryKey 约束属性设置为 true,因此使其成为主键。 列 AllowDBNull 属性设置为 false,因为主键不能有 null 值。

在转换指定有键约束的架构时,映射过程会在表中创建一个唯一约束,将约束中每个列的 AllowDBNull 列属性设置为 false。 在key元素上,IsPrimaryKey的唯一约束属性也设置为false,除非已指定msdata:PrimaryKey="true"。 这与架构 PrimaryKey="true"中的唯一约束相同。

在以下模式示例中,key元素指定了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>

key元素指定元素的CustomerIDCustomers子元素的值必须具有唯一值,并且不能具有 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

在生成的DataSet中,由于架构在key元素中指定msdata:PrimaryKey="true",因此UniqueConstraintIsPrimaryKey属性被设置为true

DataSet中的UniqueConstraintConstraintName属性的值,是在模式中的key元素中指定的msdata:ConstraintName属性的值。

另请参阅