这里是一个简单的例子,它使用了Nullables.NullableDateTime来(可选择的)保存一个人(Person)的生日。
public class Person
{
int _id;
string _name;
Nullables.NullableDateTime _dateOfBirth;
public Person()
{
}
public int Id
{
get { return this._id; }
}
public string Name
{
get { return this._name; }
set { this._name = value; }
}
public Nullables.NullableDateTime DateOfBirth
{
get { return this._dateOfBirth; }
set { this._dateOfBirth = value; }
}
}
如你所见,DateOfBirth是Nullables.NullableDateTime类型(而不是System.DateTime)。
这里是映射
%26lt;?xml version="1.0" encoding="utf-8" ?%26gt;
%26lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.0"%26gt;
%26lt;class name="Example.Person, Example" table="Person"%26gt;
%26lt;id name="Id" access="field.camelcase-underscore" unsaved-value="0"%26gt;
%26lt;generator class="native" /%26gt;
%26lt;/id%26gt;
%26lt;property name="Name" type="String" length="200" /%26gt;
%26lt;property name="DateOfBirth" type="Nullables.NHibernate.NullableDateTimeType, Nullables.NHibernate" /%26gt;
%26lt;/class%26gt;
%26lt;/hibernate-mapping%26gt;
这里是这个例子的部分代码:
Person per = new Person();
textBox1.Text = per.DateOfBirth.Value.ToString() // will throw an exception when there is no value.
textBox1.Text = per.DateOfBirth.ToString() // will work. it will return an empty string if there is no value.
textBox1.Text = (per.DateOfBirth.HasValue ? per.DateOfBirth.Value.ToShortDateString() : "Unknown") // friendly message
per.DateOfBirth = new System.DateTime(1979, 11, 8); // implicit cast from the "plain" System.DateTime.
per.DateOfBirth = new NullableDateTime(new System.DateTime(1979, 11, 8)); // the long way.
per.DateOfBirth = null; // this works.
per.DateOfBirth = NullableDateTime.Default; // this is more correct.