我打算对 Diego 的帖子发表评论,但它太长了,我想要语法突出显示。我修改了 Diego 发布的 XmlDocType,以便它使用 xml 序列化来往来于强类型对象。
我制作了自己的通用 IUserType 来处理强类型:
//you'll need these at the top of your file
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using NHibernate.UserTypes;
//using NHibernate.SqlTypes;
//using System.Data;
//using System.Xml;
//using NHibernate.Type;
[Serializable]
public class XmlType<T> : MutableType
{
public XmlType()
: base(new XmlSqlType())
{
}
public XmlType(SqlType sqlType)
: base(sqlType)
{
}
public override string Name
{
get { return "XmlOfT"; }
}
public override System.Type ReturnedClass
{
get { return typeof(T); }
}
public override void Set(IDbCommand cmd, object value, int index)
{
((IDataParameter)cmd.Parameters[index]).Value = XmlUtil.ConvertToXml(value);
}
public override object Get(IDataReader rs, int index)
{
// according to documentation, GetValue should return a string, at list for MsSQL
// hopefully all DataProvider has the same behaviour
string xmlString = Convert.ToString(rs.GetValue(index));
return FromStringValue(xmlString);
}
public override object Get(IDataReader rs, string name)
{
return Get(rs, rs.GetOrdinal(name));
}
public override string ToString(object val)
{
return val == null ? null : XmlUtil.ConvertToXml(val);
}
public override object FromStringValue(string xml)
{
if (xml != null)
{
return XmlUtil.FromXml<T>(xml);
}
return null;
}
public override object DeepCopyNotNull(object value)
{
var original = (T)value;
var copy = XmlUtil.FromXml<T>(XmlUtil.ConvertToXml(original));
return copy;
}
public override bool IsEqual(object x, object y)
{
if (x == null && y == null)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return XmlUtil.ConvertToXml(x) == XmlUtil.ConvertToXml(y);
}
}
//the methods from this class are also available at: http://blog.nitriq.com/PutDownTheXmlNodeAndStepAwayFromTheStringBuilder.aspx
public static class XmlUtil
{
public static string ConvertToXml(object item)
{
XmlSerializer xmlser = new XmlSerializer(item.GetType());
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
xmlser.Serialize(ms, item);
UTF8Encoding textconverter = new UTF8Encoding();
return textconverter.GetString(ms.ToArray());
}
}
public static T FromXml<T>(string xml)
{
XmlSerializer xmlser = new XmlSerializer(typeof(T));
using (System.IO.StringReader sr = new System.IO.StringReader(xml))
{
return (T)xmlser.Deserialize(sr);
}
}
}
然后,最后,您可以使用 Fluent.NHibernate 像这样映射您的列:
public partial class MyTableEntityMap: ClassMap<MyTableEntity>
{
public MyTableEntityMap()
{
Table("MyTable");
//...
Map(x => x.MyStronglyTypedProperty).Column("SomeXmlTypeSqlColumn").CustomType(typeof(XmlType<TypeOfMyProperty>));
}
}