可空类型适合我的情况吗?
最近将我的 ASP.NET 项目从 1.1 转换为 3.5。万岁!目前正在开发一个具有一些可选字段的表单。通常,我会在代码中添加大量 if 语句,检查是否为空字段,如果有则将值设置为 0。因此,我想知道是否最好为每个字段声明私有的、可为空的变量,然后将它们添加为数据库更新的参数?使用MSSQLS 2000,已将相应字段设置为允许空值。
澄清一下:网络表单有美元金额字段。输入的默认值为 0,但如果用户删除其中一个 0,使字段留空然后提交表单,则该方法的参数列表中的 Convert.ToDecimal(MoneyField.Text) 将引发异常将所有这些提交到数据库。有没有一种更干净的方法可以做到我所缺少的?
Recently converted my ASP.NET project from 1.1 to 3.5. Hooray! Currently developing a form which has a handful of optional fields. Normally, I'd go through in my code, adding tons of if statements, checking for empty field, and setting value to 0 if so. So, I'm wondering if it would be best to instead, declare private, nullable variables for each of these fields, then add these as parameters for my database update? Using MSSQLS 2000, already set the corresponding fields to allow nulls.
To clarify: The web form has fields for dollar amounts. The default value on the inputs is 0, but if the user deletes one of those 0's, leaving the field empty then submits the form, an exception will be thrown at Convert.ToDecimal(MoneyField.Text) in the argument list of the method that submits all this to the database. Is there a cleaner way to do this that I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
拥有这么多真正可以为空的字段似乎很不寻常,但是如果您需要将“无值”单独描述为(例如)的任何神奇域值一个
int
,那么是:Nullable
可能会有所帮助。请注意,您必须在数据层手动将null
转换为DbNull.Value
,如SqlParameter
上的null
> 表示“不发送此参数”,不“发送值null
”(如果您看到区别)。It seems unusual that you would have that many fields that are truly nullable, but if you need to describe "no value" separately to any magic domain value of (for example) an
int
, then yes:Nullable<T>
may help. Note that you must manually translate fromnull
toDbNull.Value
at the data-layer, asnull
on aSqlParameter
means "don't send this parameter", not "send the valuenull
" (if you see the distinction).我认为这里的字段验证和可为空类型之间存在混淆...当然,除非您有某种类型...例如
DateTime
并希望其为空...这是不可能的除非使用可空类型。如果是这种情况,那么……是的……可空类型就是解决方案。
I think there is mix up between field validation and Nullable Type here...unless of course you have a some type ...say
DateTime
and want that to be null...which would not be possible unless usage of Nullable Type.If that is the case then ...yes..Nullable types are the solution.
是的,听起来像是一个计划。
不过你必须改变几个电话
Yup, sounds like a plan.
You'd have to change a couple of calls though
根据提供的字段动态构建您的 sql。
Dynamically build your sql based upon the fields supplied.