2013-12-23 52 views
0

我是WCF中的新成員,我只想返回Id與客戶端提供的Id匹配的所有對象/記錄。直到現在,我只是讓WCF逐個返回對象。按照我的代碼:WCF - 按ID返回所有行到XML

的操作和數據合同:

[ServiceContract] 
public interface IVdnLoginService 
{ 
    [OperationContract] 
    VdnLoginDac GetVdnByLoginDac(string loginDac); 
} 


[DataContract] 
public class VdnLoginDac 
{ 
    [DataMember] 
    public int VdnLoginDacId { get; set; } 
    [DataMember] 
    public long VdnId { get; set; } 
    [DataMember] 
    public string VdnName { get; set; } 
    [DataMember] 
    public long EmployeeId { get; set; } 
    [DataMember] 
    public string LoginDacName { get; set; } 
} 

的服務翻譯EF模型我的自定義模型:

public class VdnLoginService : IVdnLoginService 
{ 
    public VdnLoginDac GetVdnByLoginDac(string loginDac) 
    { 
     Entities dbContext = new Entities(); 
     var VdnEntity = (from v 
          in dbContext.LOGINVDNNAMES 
          where v.LOGIN == loginDac 
          select v).FirstOrDefault(); 
     if (VdnEntity != null) 
     { 
      return TranslateLoginVdnNamesEntityToVdnLogin(VdnEntity); 
     } 
     else 
     { 
      throw new Exception("Vdn invalido"); 
     } 
    } 

    private VdnLoginDac TranslateLoginVdnNamesEntityToVdnLogin(LOGINVDNNAMES LoginVdnNamesEntity) 
    { 
     VdnLoginDac vdnLoginDac = new VdnLoginDac(); 
     vdnLoginDac.VdnLoginDacId = LoginVdnNamesEntity.VDNEMPLOYEEID; 
     vdnLoginDac.EmployeeId = LoginVdnNamesEntity.EMPLOYEEID; 
     vdnLoginDac.LoginDacName = LoginVdnNamesEntity.LOGIN; 
     vdnLoginDac.VdnId = LoginVdnNamesEntity.VDNID; 
     vdnLoginDac.VdnName = LoginVdnNamesEntity.VDNNAME; 

     return vdnLoginDac; 

    } 

} 

我知道,如果我把FirstOrDefault()關閉,我將能夠檢索所有記錄,但我不知道WCF將如何讀取所有數據。

回答任何建議將非常apreciated =)

回答

0

有兩件事情可以做,以使集合返回。

首先,將方法的返回類型從VdnLoginDac更改爲List<VdnLoginDac>,以便您可以返回匹配記錄的列表。

其次,在您的實現方法與ToList()取代FirstOrDefault(),而做的個人記錄的映射VdnLoginDac查詢,像這樣:

public List<VdnLoginDac> GetVdnByLoginDac(string loginDac) 
{ 
    Entities dbContext = new Entities(); 
    var VdnEntity = (from v 
         in dbContext.LOGINVDNNAMES 
         where v.LOGIN == loginDac 
         select new VdnLoginDac() { 
          VdnLoginDacId = v.VDNEMPLOYEEID, 
          EmployeeId = v.EMPLOYEEID, 
          LoginDacName = v.LOGIN, 
          VdnId = v.VDNID, 
          VdnName = v.VDNNAME 
         }).ToList(); 

    return VdnEntity; 
} 

注意,有一個爲沒有檢查是否VdnEntity爲空或計數爲0.客戶端應該檢查,而不是讓服務拋出異常。如果該異常未被服務處理,則會導致服務停止,並且客戶端的通信通道將處於故障狀態。

+0

蒂姆,現在工作!另外,你對例外的解釋非常好!非常感謝你! – FelipeFV