Serialize DetachedCriteria with nHibernate

狂风中的少年 提交于 2019-12-22 11:29:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!