16 Dec
Arif Khan 0 Comments

Extending WCF Data Service Entities

When we reference a WCF Data Service, entities are generated on the client side. If we examine Reference.cs file under the service reference, we can find all entities in there. We can then use these entities on our client side code.

Now there are times when we need to add more properties to these entities that do not need to be saved to the database but are required for the client UI. This is specifically the case for MVC or MVVM based clients. 

When using WPF, we would normally require our view models to do some kind of validation by implementing IDataErrorInfo interface. Or add a property to the view model that is only required for the view but not required to be persisted in the database.

To create these view models, we can use the generated entities or create our own hand-crafted view model with all the required properties.

Let us see how we can use the generated entities as view models. In order to do this, we will use the power of Partial classes.

Going back to the Reference.cs file, we notice 2 things:

The entities implement INotifyPropertyChanged interface and the classes are marked as Partial. 
 


Since Reference.cs is a generated file, we cannot make changes to it. We will create a new Partial class and make our changes there.

The image below such as an example:
   
We can implement IDataErrorInfo for validation and add our properties to it without the danger of them being overwritten when service reference is updated.

The code above shows two properties: an internal read-only and public read-write. We are not going to have any issues with read-only properties as they will be skipped by the serialization process when entities are sent to the data service.

For read-write properties, we need to ensure they are skipped during the serialization of entities otherwise we will get errors as the data service will not know anything about these new properties. So to circumvent this issue, we can create an attribute, SkipSerialization in our case, which will exclude these properties from serialization process.

So let's create an attribute as show below:
  To implement this, we need to again use the power of Partial classes. We will create the entity class using partial. This is the same class that you will find in Reference.cs and it inherits from DataServiceContext.

We will then take control of the event where it serializes the entities, i.e. WritingEntity, and write code that will skip the properties marked with SkipSerialization attribute:


Now we can extend the entities at will without worrying about code file regeneration.

 
Comments
Blog post currently doesn't have any comments.
 Security code