问题描述
我试图使用DataSet设计器创建一个查询的DataTable。我这下就好了。用于查询返回从数据库中可空datetime列。但是,当它到达围绕这个代码:
I'm attempting to use the DataSet designer to create a datatable from a query. I got this down just fine. The query used returns a nullable datetime column from the database. But, when it gets around to this code:
DataSet1.DataTable1DataTable table = adapter.GetData();
这将引发从StrongTypingException:
This throws a StrongTypingException from:
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public System.DateTime event_start_date {
get {
try {
return ((global::System.DateTime)(this[this.tableDataTable1.event_start_dateColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'event_start_date\' in table \'DataTable1\' is DBNull.", e);
}
}
set {
this[this.tableDataTable1.event_start_dateColumn] = value;
}
}
我如何使用设计,让此列可为空?
How do I use the designer to allow this column to be Nullable?
推荐答案
类型的数据集不支持可空类型。它们支持可为空的列的
Typed data sets don't support nullable types. They support nullable columns.
该类型的数据集生成器创建非空的性能和处理空值的相关方法。如果创建类型的数值指明MyDate
列的DateTime
和 AllowDbNull
设置为真正
的的DataRow
子类会实现一个非空的的DateTime
属性命名数值指明MyDate
,一个 SetMyDateNull()
方法,以及 IsMyDateNull()
方法。这意味着,如果你想在你的代码中使用可空类型,你必须要做到这一点:
The typed data set generator creates non-nullable properties and related methods for handling null values. If you create a MyDate
column of type DateTime
and AllowDbNull
set to true
, the DataRow
subclass will implement a non-nullable DateTime
property named MyDate
, a SetMyDateNull()
method, and an IsMyDateNull()
method. This means that if you want to use a nullable type in your code, you have to do this:
DateTime? myDateTime = myRow.IsMyDateNull() ? null : (DateTime?) row.MyDate;
虽然这并不完全的破坏使用类型化数据集的目的,真的很讨厌。这是令人沮丧的类型的数据集执行的方式,它比 System.Data这
扩展方法较少使用,比如空列。
While this doesn't totally defeat the purpose of using typed data sets, it really sucks. It's frustrating that typed data sets implement nullable columns in a way that's less usable than the System.Data
extension methods, for instance.
时尤其糟糕,因为输入的数据集做的一些地方使用可空类型 - 例如,在添加<表名>行()
包含上述可空的DateTime列的表法将采取的DateTime?
参数。
Is particularly bad because typed data sets do use nullable types in some places - for instance, the Add<TableName>Row()
method for the table containing the nullable DateTime column described above will take a DateTime?
parameter.
很久以前,我问在MSDN论坛上这个问题,最终实现了ADO项目经理解释说,可空类型是在同一时间类型的数据集执行,他的团队没有时间充分整合两家通过.NET 2.0的发货日期。到目前为止我可以告诉大家,他们并没有增加新的功能,自那时以来,类型化的数据集。
Long ago, I asked about this issue on the MSDN forums, and ultimately the ADO project manager explained that nullable types were implemented at the same time as typed data sets, and his team didn't have time to fully integrate the two by .NET 2.0's ship date. And so far as I can tell, they haven't added new features to typed data sets since then.
这篇关于表可为空的日期时间,但数据集抛出一个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!