数据绑定中的可为空数据类型?
我在 C# 应用程序中使用类型化数据集与数据库进行通信。我的数据库支持并允许许多记录上存在空值。但是,尝试通过数据集访问空值似乎会导致强制转换异常。
是否可以使属性可为空(至少是可以在数据库中存储空值的属性)?如果不是的话为什么要这样设计呢?
I'm using Typed Data sets in my C# application to communicate with the database. My database supports and allows null values on many of the records. However, it seems that trying to access a nulled value through the dataset results in a Cast exception.
Is it possible to make the properties nullable (atleast the ones that can store a null value in the database)? If not why was it designed this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
否,生成器工具不支持此操作。
数据集可追溯到 Fx 1.1 ,可空值类型可追溯到 Fx 2.0
当 Fx2 发布时,决定不更改类型化数据集框架(可能是出于成本和时间原因)。
从那时起,数据集框架就没有更新过,我认为在某个地方有一个官方声明,它们处于生命周期结束阶段。
No, the Generator tool does not support this.
The Dataset dates back to Fx 1.1 , nullable value types to Fx 2.0
When Fx2 was released it was decided not to change the Typed Dataset framework (for cost and time reasons presumably).
The Dataset framework has not been updated since, I think there is an official statement somewhere they're in an end-of-life stage.
在此答案中 - 类型化数据集可为空的支持< /a> 他们(MSFT)说类型数据集不支持 dot net 4.0 中的可为空值
In this answer - Typed DataSet nullable support they (MSFT) says type dataset doesn't support nullable values in dot net 4.0
虽然您无法在类型化
DataSet
中存储可为 null 的值类型,但您可以使数据集列接受DBNull
值 (column.AllowDBNull = true;
)并创建一对辅助函数来为您进行翻译。然后可以像这样使用它们:
这应该会稍微减轻疼痛。
它可能是出于历史原因而设计成这种方式的,这些历史原因与数据库
NULL
值(含义:该值未知)和 C#null
引用(含义:该参考尚未分配)。当然,在可为空值类型添加到 C# 后,这些含义发生了变化,但那时类型化DataSet
的船已经起航了。Although you cannot store nullable value types in a typed
DataSet
, you can make the data set columns acceptDBNull
values (column.AllowDBNull = true;
) and create a pair of helper functions that will do that translation for you.They can then be used like this:
That should ease the pain somewhat.
It was probably designed this way for historical reasons that relate to the conceptual difference between a database
NULL
value (meaning: the value is unknown) and a C#null
reference (meaning: this reference hasn’t yet been assigned). Of course, those meanings changed after nullable value types were added to C#, but by then the typedDataSet
ship had already sailed.可以在 .NET 中创建 Nullable 值类型。您可以只使用 Nullable generic 或只是放置 ?使值类型可为空。我不确定设计者是否会为类型化数据集自动生成它们。请看
http://xtremebytes.blogspot.com/2010/12/nullable.html供参考
It is possible to create Nullable value types in .NET. You can just use Nullable generic or just put ? to make the value type nullable. I am not sure if the designer generates them automatically for a typed dataaset. Please look at
http://xtremebytes.blogspot.com/2010/12/nullable.html for reference