[NHibernate]Nullables

系列文章

[Nhibernate]体系结构

[NHibernate]ISessionFactory配置

[NHibernate]持久化类(Persistent Classes)

[NHibernate]O/R Mapping基础

[NHibernate]集合类(Collections)映射 

[NHibernate]关联映射

[NHibernate]Parent/Child

[NHibernate]缓存(NHibernate.Caches)

[NHibernate]NHibernate.Tool.hbm2net

什么是Nullables?

Nullables是NHibrnate的附加软件,它是Donald L Mull Jr.(aka luggage)贡献的,大部分数据库系统允许基本类型(int或bool)为null。这意味着一个boolean列可能有0,1或者是null值,null和0有不同的含义。但是在.NET 1.x这是不能实现的;一个bool不是true就是false。

Nullables使得在NHibernae中nullable的基本类型成为可能。注意,.NET2.0已经有了这个特性。

如何使用?

这是一个简单的例子,它使用了Nullables.NullableDateTime来(可选择)保存一个人的生日。

 1 public class Person
 2 {
 3     int _id;
 4     string _name;
 5     Nullables.NullableDateTime _dateOfBirth;
 6     public Person()
 7     {
 8     }
 9     public int Id
10     {
11         get { return this._id; }
12     }
13     public string Name
14     {
15         get { return this._name; }
16         set { this._name = value; }
17     }
18     public Nullables.NullableDateTime DateOfBirth
19     {
20         get { return this._dateOfBirth; }
21         set { this._dateOfBirth = value; }
22     }
23 }

如你所见,DateOfBirth是Nullables.NullableDateTime类型(而不是System.DateTime)。这里是映射

 1 <?xml version="1.0" encoding="utf-8" ?> 
 2 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
 3     <class name="Example.Person, Example" table="Person">
 4         <id name="Id" access="field.camelcase-underscore" unsaved-value="0">
 5             <generator class="native" />
 6         </id>
 7         <property name="Name" type="String" length="200" />
 8         <property name="DateOfBirth" type="Nullables.NHibernate.NullableDateTimeType, Nullables.NHibernate" />
 9     </class>
10 </hibernate-mapping>

重点

在这个映射中,DateOfBirth的类型必须是Nullables.NHibernate.NullableDateTimeType。注意NHibernate.Mapping.Attributes会自动处理它。
Nullables.NHibernate.NullableXXXType是用来转换Nullables 类型到数据库的包装类。

这里是这个例子的部分代码:

1 Person per = new Person();
2 textBox1.Text = per.DateOfBirth.Value.ToString() // will throw an exception when there is no value.
3 textBox1.Text = per.DateOfBirth.ToString() // will work. it will return an empty string if there is no value.
4 textBox1.Text = (per.DateOfBirth.HasValue ? per.DateOfBirth.Value.ToShortDateString() : "Unknown") // friendly message
5 per.DateOfBirth = new System.DateTime(1979, 11, 8); // implicit cast from the "plain" System.DateTime.
6 per.DateOfBirth = new NullableDateTime(new System.DateTime(1979, 11, 8)); // the long way.
7 per.DateOfBirth = null; // this works.
8 per.DateOfBirth = NullableDateTime.Default; // this is more correct.

本文来自《NHibernate 中文文档》

 

posted @ 2014-05-18 11:09  wolfy  阅读(973)  评论(1编辑  收藏  举报