Search code examples
silverlightwcfcode-reusedatacontract

How to share entity C# class, with DataContract attribute, between Silverlight and.Net 4 projects


I want to build a WCF REST service, consumed by a Silverlight app, and want to check if there is a good way to share the entity class between the web wcf project and the Silverlight project (they are two different CLR types). The code is essentially the same for both projects: entity class decorated with DataContract attribute and properties with DataMember attribute.


Solution

  • What I've usually done and works quite well is to have the data contracts in one of the projects (e.g., the web project) and on the SL projects I add them as links (right-click on the project, add existing item, select files, then instead of clicking the "Add" button, choose the drop down and select "Add as link"). This way the types are shared between both projects.

    Notice that this is even possible to do for service contracts, but since SL doesn't support synchronous operation calls, I usually use some compiler directives to be able to share the service contract, like in the example below.

    [ServiceContract]
    public interface ITest
    {
    #if SILVERLIGHT
        [OperationContract(AsyncPattern = true)]
        IAsyncResult BeginAdd(int x, int y, AsyncCallback callback, object state);
        int EndAdd(IAsyncResult asyncResult);
    #else
        int Add(int x, int y);
    #endif
    }