OperationContract的集合返回类型以及如何添加到DataContracts列表中?

时间:2014-05-02 09:50:19

标签: c# wcf list datacontract operationcontract

我有一个业务领域对象( BDO )类:

public class BDO_LIST_DEPARTMENTS
{
    public int DEPARTMENT_ID { get; set; }
    public string DEPARTMENT_NAME { get; set; }
}

然后我有一个DataContract课程:

[DataContract]
public class DC_LIST_DEPARTMENTS
{
    [DataMember]
    public int DEPARTMENT_ID { get; set; }

    [DataMember]
    public string DEPARTMENT_NAME { get; set; }
}

在我的服务层中,我尝试将 BDO 转换为DataContract,然后返回此DataContract的列表,作为{的返回类型{1}}:

OperationContract

这是我在服务层中的原始尝试:

[OperationContract]
    IList<DC_LIST_DEPARTMENTS> GetAllDepartments();

正如您所看到的,我尝试向public IList<DC_LIST_DEPARTMENTS> GetAllDepartments() { DC_LIST_DEPARTMENTS DCDepartment = new DC_LIST_DEPARTMENTS(); IList<DC_LIST_DEPARTMENTS> DCListOfDepartments = new List<DC_LIST_DEPARTMENTS>(); ICollection<BDO_LIST_DEPARTMENTS> BDOListOfDepartments = Bal.GetAllDepartments(); foreach (BDO_LIST_DEPARTMENTS BDODepartment in BDOListOfDepartments) { DCDepartment.DEPARTMENT_ID = BDODepartment.DEPARTMENT_ID; DCDepartment.DEPARTMENT_NAME = BDODepartment.DEPARTMENT_NAME; DCListOfDepartments.Add(DCDepartment); } return DCListOfDepartments; } 添加一个DataContract,但是当我这样做时,它会将该列表中的其他每个项目更改为相同的IList<DataContract>具有相同的细节。

因此,我的问题是,DataContract的正确返回类型是什么,如何返回OperationContract类的列表以及如何在不更改的情况下添加到该列表列表中所有其他项目的数据?

1 个答案:

答案 0 :(得分:0)

定义集合数据合约

[CollectionDataContract]
public class DC_LIST_DEPARTMENTS_LIST : List<DC_LIST_DEPARTMENTS> {
  ...
}

并使用此集合数据协定作为返回类型的操作方法。

public DC_LIST_DEPARTMENTS_LIST  GetAllDepartments() {
   ...
}

以下是服务方法的修改实现:

public DC_LIST_DEPARTMENTS_LIST   GetAllDepartments() {

            IList<DC_LIST_DEPARTMENTS> DCListOfDepartments = new List<DC_LIST_DEPARTMENTS>();
            ICollection<BDO_LIST_DEPARTMENTS> BDOListOfDepartments = Bal.GetAllDepartments();

            foreach (BDO_LIST_DEPARTMENTS BDODepartment in BDOListOfDepartments) {
                DC_LIST_DEPARTMENTS DCDepartment = new DC_LIST_DEPARTMENTS() {
                    DEPARTMENT_ID = BDODepartment.DEPARTMENT_ID,
                    DEPARTMENT_NAME = BDODepartment.DEPARTMENT_NAME
                };
                DCListOfDepartments.Add(DCDepartment);
            }

            return DCListOfDepartments;
        }