Search code examples
c#wcfdatacontract

WCF: How do i return a .NET Framework class via Datacontract?


As a beginner to WCF i want to implement a call to the Active Directory Service which gets all Users, the method looks like this:

    [OperationContract]
    SearchResultCollection GetAllUsers();

SearchResultCollection is not serializable so i have to make something like this:

[DataContract] SearchResultCollection

So i have to make my own wrapper class which inherits the SearchResultCollection or use IDataContractSerializer. Both solutions seems not easy.

The question: How is the "standard" approach to use .NET Classes as a return type in a WCF service?

(Writing a own DataContract for my own class seems easy. ;))


Solution

  • I think your best bet is create your own simple POCO class to represent SearchResult, and return a list of these objects. Really you want to be able to control exactly the information you need to send back from the service. For example:

    [Serializable]
    public class MySearchResult
    {
        public string Name { get; set; }
    
        public string Email { get; set; }
    }
    

    And simply iterate the searech results and pull out the properties you need like so:

    var results = new List<MySearchResult>();
    
    foreach (SearchResult r in searchResultCollection)
    {
        results.Add(new MySearchResult
                        {
                            Name = searchResult.Properties["Name"],
                            Email = searchResult.Properties["Email"]
                        });
    }
    

    That way the xml being sent back isn't bloated with all the properties you don't need AND you can serialize your own List<MySearchResult> return results. And by the way I have no idea if the Name and Email properties exist I am just showing an example.