0

我使用此代码从我的数据库中获取数据

var table = kantarDataSetTartimlarTableAdapter.GetData().Select(s =>  new
                    {
                        s.DateColumn,
                        s.Index
                    }).AsEnumerable().Select ((s, column) => new
                                          {                                                  
                                              s.DateColumn,                                                  
                                              s.Index                                                  
                                              column_no = column + 1
                                          });

如果date column不是null,我没有任何问题。但是当date columnnull数据时我有问题:

[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;
}

}

我该如何解决这个错误?

4

3 回答 3

1

您的数据库列和实体模型似乎不同步。如果您null从数据库中取回一个值,那么该字段必须是可空的。为了映射到您的模型,它还必须支持可为空的日期。

您需要更新event_start_date模型以使用Nullable<DateTime>/ DateTime?

于 2013-07-16T15:02:57.050 回答
0

您可以在从数据库中读取值时尝试提供默认值,以确保您没有存储任何空值:

DateColumn = s.DateColumn ?? DateTime.MinValue
于 2013-07-16T15:06:46.493 回答
0

我更新event_start_date并解决了我的问题

get {
                try {
                    if (this[this.table.DateTimeColumn] is DBNull)
                    {
                        return Convert.ToDateTime(null);
                    }
                    else
                    {
                        return ((global::System.DateTime)(this[this.table.DateTimeColumn]));
                    }
                }
                catch (global::System.InvalidCastException e) { 
                    throw new global::System.Data.StrongTypingException("Description", e);                        
                }
            }

            set {
                this[this.table.DateTimeColumn] = value;
            }
于 2013-07-17T07:03:33.487 回答