问题
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:
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();
来源:https://stackoverflow.com/questions/792289/serialize-detachedcriteria-with-nhibernate