有时候在NHibernate中的基本数据类型可能不够好用,可以考虑自定义一个数据类型。

可以通过实现IUserType或者ICompositeUserType接口来实现这一功能。 ICompositeUserType较IUserType而言可以提供更多的控制。一般情况我们实现IUserType即可。

IUserType Members

Public Instance Properties

IsMutable Are objects of this type mutable?
ReturnedType The type returned by NullSafeGet()
SqlTypes The SQL types for the columns mapped by this type.

Public Instance Methods

DeepCopy Return a deep copy of the persistent state, stopping at entities and at collections.
Equals Compare two instances of the class mapped by this type for persistent "equality" ie. equality of persistent state
NullSafeGet Retrieve an instance of the mapped class from a JDBC resultset. Implementors should handle possibility of null values.
NullSafeSet Write an instance of the mapped class to a prepared statement. Implementors should handle possibility of null values. A multi-column type should be written to parameters starting from index.

 比如:我想实现在数据库里存储格式为“数据;数据;数据”,而在类中体现为IList。这样我们可以减少一些一对多的映射。我们可以用它来存放EMail等数据。

自定义数据类:

using System;
using System.Collections;
using System.Data;
using System.Text;
using NHibernate;
using NHibernate.SqlTypes;

namespace Index.Data.NHibernateHelper
{
    
/// <summary>
    
/// 自定义的NH数据类型,使用;分隔存储多个数据
    
/// </summary>

    public class DDLList : IUserType
    
{
        
private static readonly char SPLITTER = ';';

        
private static readonly SqlType[] TYPES = new SqlType[] {NHibernateUtil.String.SqlType};

        
IUserType 成员

        
/// <summary>
        
/// 将string拼装成一个字符串,以“;”分隔
        
/// </summary>
        
/// <param name="list"></param>
        
/// <returns></returns>

        private string ListToString(IList list)
        
{
            
if (list.Count == 0)
            
{
                
return null;
            }

            StringBuilder sb 
= new StringBuilder();
            
for (int i = 0; i < list.Count - 1; i++)
            
{
                sb.Append(list[i]).Append(SPLITTER);
            }

            sb.Append(list[list.Count 
- 1]);
            
return sb.ToString();
        }


        
/// <summary>
        
/// 将“;”分隔的字符串解析为数组
        
/// </summary>
        
/// <param name="value"></param>
        
/// <returns></returns>

        private IList StringToList(string value)
        
{
            
string[] strs = value.Split(SPLITTER);
            IList emailList 
= new ArrayList();
            
for (int i = 0; i < strs.Length; i++)
            
{
                emailList.Add(strs[i]);
            }

            
return emailList;
        }

    }

}

在映射文件中如此设置
    <property name="Email1" type="Index.Data.NHibernateHelper.DDLList,Index.Data.NHibernateHelper" column="Email1" />

在实体类中直接使用IList映射即可。