I got a problem. This my code use a LINQ.
var resultCases = from row2 in dtCases.AsEnumerable()
where row2.Field<int>("caseID") == caseID2
select new
{
caseName = row2["caseName"].ToString(),
caseCourtPlace = row2["caseCourtPlace"].ToString(),
caseCourtRef = row2["caseCourtRef"].ToString(),
caseOfficeRef = row2["caseOfficeRef"].ToString(),
effectiveDate = ((DateTime)row2["caseEffectiveDate"]),
closedDate = ((DateTime)row2["caseClosedDate"]),
caseFolderPath = row2["casesFolderPath"].ToString(),
category = row2["categoryName"].ToString(),
department = row2["departmentName"].ToString(),
empName = row2["empName"].ToString(),
judgeName = row2["judgeName"].ToString(),
asName = row2["asCasesName"].ToString(),
};
If closedDate or effectiveDate return DBnull.Value, I get
InvalidCastException was unhandled – Specified cast is not valid.
So how can I prevent this error?
tldr; The issue is two-fold: DataTable uses
DBNull.Valueto represent “null” values and neitherDBNull.Valueornullare castable toDateTime.The
Field<T>extension method was added later to make dealing with DBNull and Nullable/reference types with null values much easier; it also hides the conversion behind a strongly-typed signature. These LINQ to DataSet extension method knows how to mapDBNull.Valuetonullas appropriate.Because of this using
row.Field<DateTime?>("caseEffectiveDate")will return either theDateTime?with a value (if the query returned a value) ornull, and it may also throw an exception if the server returned an incompatible value – but it will never returnDBNull.Value.However, the standard
row["caseEffectiveDate"]will return aDateTimevalue (or some other type) orDBValue.Nullwhich is not cast-able toDateTime?(much less aDateTime) and results in the error described.Here is how to minimally reproduce this exception:
However, it is fine to convert a
nullto aDateTime?:And then trivial to coalesce it away to
DateTimeif required: