目录
- 如何使用?
什么是 Nullables?
Nullables 是 NHibernate 的附加软件,它是Donald L Mull Jr. (aka luggage)贡献的.大部分数据库系统允许基本类型(象int
或bool
)为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 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.
分类:
NHibernate
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构