3

I am trying to serialize a DetachedCriteria so I can save it in a database and reuse the same criteria at a later date. When I run the code below I get "NHibernate.Criterion.DetachedCriteria cannot be serialized because it does not have a parameterless constructor".

DetachedCriteria criteria1 = DetachedCriteria.For<SecurityObjectDTO>("so")
    .Add(Expression.Eq("ObjectCode", "1234"));

XmlSerializer s = new XmlSerializer(typeof(DetachedCriteria));
TextWriter writer = new StringWriter();
s.Serialize(writer, criteria1);
writer.Close();

Is there any good way to serialize a DetachedCriteria?

Craig
  • 36,306
  • 34
  • 114
  • 197
  • So the user can create a criteria which I can then save in the database for later reuse. – Craig Apr 27 '09 at 21:28

1 Answers1

1

I've run into something similar before. My first thought was to subclass DetachedCriteria so you could provide a default constructor yourself. However, after digging through the DetachedCriteria class, I don't think this will work. The reason is the CriteriaImpl class, used internally by DetachedCriteria, is also lacking a default constructor.

Looking at XmlSerializer, it doesn't look like it will work if your object doesn't have a default constructor.

I ran into this post, however:

How do I serialize an NHibernate DetachedCriteria object?

Based on that, this might work (I haven't tested it, however):

// Convert the DetachedCriteria to a byte array
MemoryStream ms = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, detachedCriteria);

// Serialize the byte array
XmlSerializer s = new XmlSerializer(typeof(byte[]));
TextWriter writer = new StringWriter();
s.Serialize(writer, ms.Buffer);
writer.Close();
Community
  • 1
  • 1
Doug
  • 5,208
  • 3
  • 29
  • 33
  • 2
    As an aside, I'd think about finding an alternate way to represent your criteria. If you could represent it as a string or XML value, then you could greatly simplify your serialization process. – Doug Dec 09 '09 at 16:21
  • 1
    What about deserializing to DetachedCriteria? – Mike de Klerk Nov 01 '13 at 09:47