Using Entity Framework Self Tracking Entities with AppFabric CACHE (‘Velocity’) and .NET 4.0 RTM
Currently, when you try to use Entity Framework STE (Self Tracking Entities) and AppFabric-Cache (aka. “Velocity”), you’ll get a runtime error.
I mean, what we’re trying to do is trying to serialize STE objects within AppFabric-Cache. For instance, we could try to execute the following code, using AppFabric Cache API:
var cacheContainer = this._cacheFactory.GetCache(container);
Where, in this case, the ‘value’ parameter would be an EF STE object or collection, ok?
Then, when trying to execute that Put() command to store it within AppFabric, you’ll get the following “nice” error:
System.Runtime.Serialization.InvalidDataContractException was unhandled by user code
Message=Type ‘XXXXXXXXXXXXXXXXXX.Entities.TrackableCollection`1[XXXXXXXXXXXXXXXXXXXXXXXXXXxx.MyEntity]’ cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute.
The problem is that by default the TrackableCollection<T> in the Types.tt file (T4 template), is not marked with a [CollectionDataContract] attribute.
You can fix this by going to Line 1401 in the in the Types.tt (usually it is that line number) and adding the [CollectionDataContract] attribute like the following:
public class TrackableCollection<T> : ObservableCollection<T>
Then, you’ll be able to serialize and store your Entity Framework Self Tracking Entities within AppFabric CACHE. 🙂
BTW, I think that the same problem could arise if you try to use Workflow Foundation Persistence and Entity Framework STE (Self Tracking Entities). Its workaround could be the same.