NHibernate文档翻译 第11章----Nullables

来源:互联网 发布:下载一个软件 编辑:程序博客网 时间:2024/06/05 10:38
第11章 Nullables

目录

如何使用?

什么是 Nullables?

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

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

如何使用?

这里是一个简单的例子,它使用了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)。

这里是映射

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

在这个映射中,DateOfBirth的类型必须Nullables.NHibernate.NullableDateTimeType。注意NHibernate.Mapping.Attributes会自动处理它。

Nullables.NHibernate.NullableXXXType是用来转换Nullables 类型到数据库的包装类。

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

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 messageper.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.
原创粉丝点击