2015-10-16 197 views
0

我有被放置在一個類庫類:WCF處理對象

public class UserProfile 
{ 
    public int UserId { get; set; } 
    public string UserName { get; set; } 
} 

然後,我有一個倉儲類:

public class Repository 
{ 
    public List<UserProfile> GetUsers() 
    { 
     using (var context = new DBContext()) 
     { 
      List<UserProfile> list = context.UserProfiles.ToList(); 
      return list; 
     } 

    } 
} 

業務邏輯類:

public class BusinessLogic 
{ 
    public List<UserProfile> GetUserProfiles() 
    { 
     Repository repo = new Repository(); 
     List<UserProfile> list = repo.GetUsers().ToList(); 
     return list; 
    } 
} 

和最後的WCF:

public interface IService1 
{ 
    [OperationContract] 
    List<UserProfile> GetUserProfiles(); 
} 


public class Service1 : IService1 
{ 
    public List<UserProfile> GetUserProfiles() 
    { 
     BusinessLogic.BusinessLogic bl = new BusinessLogic.BusinessLogic(); 
     List<UserProfile> list = bl.GetUserProfiles().ToList(); 
     return list; 
    } 
} 

每當我嘗試從wcf獲取用戶配置文件時,它都會返回空列表。

但是,如果我跳過wcf並直接從businesslogic中獲得List<UserProfile>,那麼它工作得很好。

我試圖調試。結果:當在wcf裏面從businesslogic獲取列表時,它已經是空的。但正如我剛纔所說,業務邏輯完美地工作(返回必要的信息)。

有類似的帖子,但沒有人幫我。

如何讓我的WCF返回一個填充必要信息的列表?

P.S.我不想將我的類UserProfile的副本添加到wcf中[DataContract]標記

+0

你爲什麼要在各個層次上調用'ToList()'?您的存儲庫已經返回'IList',因此可以安全地移除對'BusinessLogic'和'Service1'中的'ToList'的調用。 要嘗試的另一件事是,在庫中添加對'System.Runtime.Serialization' dll的引用,並在其中聲明'UserProfile'並在其上添加'[DataContract]'屬性。看看是否有幫助,儘管我會嘗試在WCF方法中放置一個斷點,並調用bl.GetUserProfiles()來查看返回的列表是空的。 – Michael

+0

我知道,起初我以爲這個問題與WCF處理列表有關,所以我寫了.ToList()來確保。是的,它是安全的刪除它們,你是對的 – Tautvydas

回答

2

您的對象必須是可序列化的或使用該DataContract屬性進行修飾。您的WCF返回類型也必須使用DataContract屬性進行修飾,並且包含List的成員必須使用DataMember屬性進行標記。這是WCF的DataContractSerializer必需的,以便正確序列化數據並將其返回給使用者。轉換類以通過電線傳輸需要序列化。用WCF解決這個問題沒有一個實際的方法。

您的列表爲空,因爲您的UserProfile類不能被序列化。

編輯:

我剛纔看見你只是返回一個列表,這已經是系列化,所以,如果你只是讓你的用戶配置類序列化或相應DataContract /數據成員類裝飾它,它就會開始工作正常。

+0

但我已閱讀其他帖子,現在不需要使用DataContract屬性。 因此,如果我讓我的對象可序列化,我可以保存在類庫中的wcf之外,它應該工作正常嗎? – Tautvydas

+2

@Tautvydas你可以使用'DataContract'屬性不需要共享的任何鏈接?我發現[完全相反](http://stackoverflow.com/questions/438669/how-do-you-return-a-user-defined-type-from-a-wcf-service)。 – Michael

+0

您可以使用DataContract屬性(與DataContractSerializer相關)或Serializable屬性,但該類必須以某種方式可序列化。 WCF在傳輸之前序列化數據。 請記住,該類不必位於您的WCF類庫中。您可以將任何庫中的任何類標記爲DataContract或可序列化的。我一直這樣做(將業務對象放在單獨的庫中)並且工作正常。 – DVK