POCO 对象中的非空约束
我目前正在编写一个财务应用程序,我们有一个非常标准的客户表。 它由许多必填字段和一些可选字段(例如 Cell/Fax 等)组成。我使用 NHibernate 作为 ORM,并且所有映射都是正确的。 它已经起作用了。
我只是想知道,如何在代码中“表达”字段不为空而无需注释? 我有 hbm.xml 文件来记录这一点,但是查看它们来查找此类内容有点尴尬。
我想到的另一件事是,我不希望存储库在我的逻辑中抛出 NHibernate 异常,所以也许我应该在控制器中采用验证路径。 不过,如何让 POCO 代码表示某些字段可以为空?
如您所见,我希望蜂窝和传真是可选的而电话是强制性的。 它们都只是复合映射,因此映射文件只是指定每个元素的单个元素必须不为空,但我讨厌始终执行 Person.Cellular != null 检查以避免出现 NullReferenceException。
I am currently writing an financial application, and we have a pretty standard customer table. It consists of many mandatory fields, and some optional like Cell/Fax etc.. I'm using NHibernate as a ORM and have all the mappings right. It already works.
I just wonder, how do I "express" in code that a field is not-null without commenting? I have the hbm.xml files that document this, but it's kinda awkward to look at them for things like this.
The other thing that comes to mind is that I don't want the repository to throw NHibernate Exceptions at my Logic, so maybe I should go the validation route in the Controller.
Still, how can I make the POCO code express that some fields can be null?
As you can see, I want to have Cellular and Fax be optional while Phone mandatory. They are all just composite mappings, so the mapping file just specifies that the single elements of each have to be not-null, but I hate to do the Person.Cellular != null check all the time to avoid having a NullReferenceException.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您的 POCO 行为和编码风格,有几种方法可以实现此目的。
首先,您可以使用可为空类型来表示该字段可为空,因此隐式表明其余字段不可为空。
或者,您可以引入 Phone 值类型作为您所示的 POCO 的 Phone 属性的类型,这意味着因为它不是原始类型,所以“更重要” - 这也将使您能够在类中封装电话号码验证本身。
在我看来,要成为一个真正的 POCO 对象,它不需要担心它所在的数据库表中的底层可为空性......它实际上应该具有验证和值类型,以将其行为表达为独立实体; 因此在到达 NHibernate 之前它已经处于有效状态。
There are a few ways of doing this depending on your POCO behaviour and coding style.
Firstly, you could use nullable types to express that this field is nullable and it would therefore be implicit that the rest are not nullable.
Alternatively you could introduce a Phone value type as the type for the Phone property of the POCO you illustrated, implying that because it is not a primitive type it is "more important" - this would also enable you to encapsulate phone number validation within the class itself.
In my mind, to be a true POCO object, it need not worry about the underlying nullability within the database table it is persited in... it should actually have validation and value types that express its behaviour as a stand alone entity; thus before it gets to NHibernate it is already in a valid state.
将 notnull 属性设为只读并通过公共构造函数写入它们。 将默认构造函数设为受保护或私有。
Make notnull properties readonly and write to them via a public constructor. Make the default constructor protected or private.