Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

c# - Table is nullable DateTime, but DataSet throws an exception?

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();

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Typed data sets don't support nullable types. They support nullable columns.

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;

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...