0

I have a class which has some expression tree properties. when I try to serialize it using the serializable attribute in order to configure SQL Server Session State, I have got the following error: ..Unable to serialize the session state, SerializationException: Type 'System.Linq.Expressions.Expression..., as the picture shows.

Does anybody know how can I solve that problem to be able to manage session state on SQLServer mode. Thanks.

enter image description here

My class looks to something like this:

[Serializable]
public class Elements<T>
{
    public List<T> elementsList { get; set;}
    Expression<Func<int, bool>> lambda = num => num < 5;

}
dan richardson
  • 3,871
  • 4
  • 31
  • 38
D.B
  • 4,009
  • 14
  • 46
  • 83

1 Answers1

1

It would make no sense to serialize an Expression. You should ignore it.

[Serializable]
public class Elements<T>
{
    public List<T> elementsList { get; set;}

    [NonSerialized]
    Expression<Func<int, bool>> lambda = num => num < 5;
}

Look here for more info: https://msdn.microsoft.com/en-us/library/system.nonserializedattribute(v=vs.110).aspx

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • Thanks Jeroen, effectively the [NonSerialized] attribute worked, however I am still unsure about why I should not serialize the expressions. I have not finished to serialize all the classes required from the project so I am not sure yet if these expressions are not going to be a problem when getting the session values... ? – D.B Jun 08 '16 at 05:10
  • An expression is a function. You only serialize data. The function is constant and defined in your program. The parameters(session values) is data. – Jeroen van Langen Jun 08 '16 at 06:18
  • As you can see, your expression only contains a constant. `5`. Next time your program runs, it still will be `5`. So it won't change ever. If you want a variable, you'll have to create an additional property. `Expression> lambda = num => num < MaxValue;` But the property will be serialized, not the expression. – Jeroen van Langen Jun 08 '16 at 06:50
  • It makes more sense now. My project is working like a charm. Thanks. – D.B Jun 09 '16 at 22:49