我正在将我的DataTable转换为通用列表,并且在将行值转换为列表的对象时,它给出了Cast Exception。我尝试使用代码处理DBNull

if (dataRow["DateCompleted"] == DBNull.Value)
{
    dataRow["DateCompleted"] = null;
}
if (dataRow["TotalRecords"] == DBNull.Value)
{
    dataRow["TotalRecords"] = 0;
}
if (dataRow["CompanyName"] == DBNull.Value)
{
    dataRow["CompanyName"] = "";
}


但DateCompleted不接受null,DBNull或空字符串。

经过这个过程,我正在制作像

DemoData demoValue = new DemoData
{
    CompanyName = dataRow["CompanyName"].ToString(),
    DateCompleted = (DateTime)dataRow["DateCompleted"],
    TotalRecords = (int)dataRow["TotalRecords"]
};


并将对象添加到列表中

DataList.Add(demoValue);


我的清单是

public List<DemoData> DataList = new List<DemoData>();


我的课是

public class DemoData
{
    public string CompanyName { get; set; }
    public DateTime DateCompleted { get; set; }
    public int TotalRecords { get; set; }
}

最佳答案

如果DemoData未完成,答案取决于您要执行的业务逻辑:

您可能要坚持使用null;但是,它使逻辑更加复杂(因为null现在是一种特殊情况),并且需要进行DemoData修改:

public class DemoData
{
     public string CompanyName { get; set; }
     // DateTime? - DateCompleted is Nullable<DateTime>
     public DateTime? DateCompleted { get; set; }
     public int TotalRecords { get; set; }
}
...

DemoData demoValue = new DemoData {
  CompanyName = dataRow["CompanyName"].ToString(),
  DateCompleted = dataRow.IsDbNull("DateCompleted")
    ? null // <- now we can assign null to Nullable<T>
    : (DateTime?) dataRow["DateCompleted"],
  TotalRecords = (int)dataRow["TotalRecords"]
};


您可能希望采用以下(典型)逻辑:“如果DemoData尚未完成,它将最终在(遥远的)将来完成”:

...
if (dataRow["DateCompleted"] == DBNull.Value)
{
    // Well, at 31 Dec 9999 it'll be completed for sure...
    dataRow["DateCompleted"] = DateTime.MaxValue;
}

...

DemoData demoValue = new DemoData
{
  CompanyName = dataRow["CompanyName"].ToString(),
  DateCompleted = (DateTime)dataRow["DateCompleted"],
  TotalRecords = (int)dataRow["TotalRecords"]
};

关于c# - 处理DateTime的DBNull值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44283916/

10-12 00:28