Here I will post problems I and my colleagues met and solutions we found.

Wednesday, June 03, 2009

WCF - nullable values are not working in generics

Today I spent couple of hours figuring out why I suddenly got an error "Referenced type 'x`1, ... with data contract name 'xIF_Ph6aZR' in namespace 'x cannot be used since it does not match imported DataContract. Need to exclude this type from referenced types."

It was working and what I did just little bit of re-factoring. What I found is that there is a combination of conditions that does not work, while every one of them works separately:

  1. Generic class is used as DataContract.
  2. This class has nullable DataMember property
  3. You want to reference your class in your client instead of creating in through wsdl.

[DataContract]
public class DummnyContract<T> where T: IBusinessObject
{

[DataMember]
public DateTime? LastModified{get;set;}

}
and then you use it like this:


[ServiceContract]
public interface IService
{
[OperationContract]
DummyContract<int> Get(int id);

}

This just does not work when you reference your assembly with declaration of this class. You can have it without class being generic. Or, you can have generic without nullable property. But not together.

1 comment:

niko said...

We solved this problem by using the nullable<> or ? type in two steps:

1.)
In the class containing the generic field, define the field as follows:

nullable MyField {get; set;}

2.)
In the data contract that uses this baseclass, you can define which elements are known to the serializer/deserializer using some annotation-like tags. Here, we defined for example:

[Serializable]
[DataContract][KnownType(typeof(BaseClass>))]

After this, the serialization of generic null values worked for us.