views:

450

answers:

1

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?

+1  A: 

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:

http://stackoverflow.com/questions/1245985/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();
Doug
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