Data Contract for Dictionary 前面的内容,我们分别讨论了基于Generic和Collection的Data Contract,接下来,我们来讨论最后一个特殊的数据类型的Data Contract:Dictionary。
延续上面的Order Batch Processing的例子,不过我们现在处理的不是一个OrderCollection对象,而是一个Dictionary对象,线面是Service Contract和Order的定义:
namespace Artech.SpecialDataContract.Contract
{
[ServiceContract]
public interface IOrderManager
{
[OperationContract(Name = "ProcessWithCollection")]
void Process(OrderCollection orders);
[OperationContract(Name = "ProcessWithDictionary")]
void Process(IDictionary<Guid, Order> orders);
}
}
[DataContract]
public class Order
{
[DataMember]
public Guid OrderID
{ get; set; }
[DataMember]
public DateTime OrderDate
{ get; set; }
}
我们来看XSD:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:ser="http://schemas.microsoft.com/2003/10/Serialization/">
<xs:import schemaLocation="http://artech/Artech.SpecialDataContract/OrderManagerService.svc?xsd=xsd1" namespace="http://schemas.microsoft.com/2003/10/Serialization/"/>
<xs:import schemaLocation="http://artech/Artech.SpecialDataContract/OrderManagerService.svc?xsd=xsd2" namespace="http://schemas.datacontract.org/2004/07/Artech.SpecialDataContract.Contract"/>
<xs:complexType name="ArrayOfKeyValueOfguidOrder_SkVQi6O3">
<xs:annotation>
<xs:appinfo>
<IsDictionary xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</IsDictionary>
</xs:appinfo>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" name="KeyValueOfguidOrder_SkVQi6O3">
<xs:complexType>
<xs:sequence>
<xs:element name="Key" type="ser:guid"/>
<xs:element name="Value" nillable="true" type="q1:Order" xmlns:q1="http://schemas.datacontract.org/2004/07/Artech.SpecialDataContract.Contract"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:element name="ArrayOfKeyValueOfguidOrder_SkVQi6O3" nillable="true" type="tns:ArrayOfKeyValueOfguidOrder_SkVQi6O3"/>
</xs:schema>
Data Contract的名称为ArrayOfKeyValueOfguidOrder_SkVQi6O3=ArrayOfKeyValueOf+guid(Key的类型)+Order(Value)+_SkVQi6O3(Hash Value)。从该XSD的结构我们不难看出,只是一个数组,每个元素为Key-Value pair。
我们照例看看通过Add Service Reference方式生成的Client端code中的对应的定义:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="OrderManagerService.IOrderManager")]
public interface IOrderManager {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IOrderManager/ProcessWithDictionary", ReplyAction="http://tempuri.org/IOrderManager/ProcessWithDictionaryResponse")]
void ProcessWithDictionary(System.Collections.Generic.Dictionary<System.Guid, Artech.SpecialDataContract.Client.OrderManagerService.Order> orders);
}
生成的是一个System.Collections.Generic.Dictionary类型。同Collection一样,也依然可以有多种选择:
