SPMetal Entities Not Serializable
I recently had the pleasure of writing a SharePoint workflow and leveraging the SPMetal Tool to generate some classes for my lists and content types for which the workflow would run against. SPMetal, if you a have not played with it, is a very cool tool for generating strongly typed classes for which you can use to interact with SharePoint List data. So instead of writing code like:
item[“MyProperty”] = 10;
You instead write code like:
MyListContentTypeName.MyProperty = 10;
This will then alert you to type safety issues at compile time instead of run-time. It also prevents you from having to write CAML throughout your code! So with all that goodness SPMetal sounds like the best choice and a great alternative, and for the most part it is. One issue in particular however is that if your code needs to be serialized (in my case because of a workflow going to sleep) then you might run into some issues. One exception that recently got me was preventing me from executing my workflow. It seems there are a couple of events in the generated code that need to be marked a s “Nonserializable” for which the SPMetal tool does not handle. I have outlined the exception and the resolution below. All that needs to be done is to modify the generated code with the below attributes and all should be well.
NOTE: The drawback to all this however is that you will need to make this modification every time the SPMetal Class is regenerated.!
Here are some links to resource about SPMetal if you want to know more:
SPMetal Overview
https://msdn.microsoft.com/en-us/library/ee538255.aspx
Overridable Properties
https://msdn.microsoft.com/en-us/library/ee535056.aspx
Exception:
Type 'Microsoft.SharePoint.Linq.EntityTracker+WeakEntityNotifyHandler' in Assembly 'Microsoft.SharePoint.Linq, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' is not marked as serializable.
Members to Mark:
[field:NonSerializedAttribute]
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
[field: NonSerializedAttribute]
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
Thanks to Neil Burns for pointing this one out!