“Specified cast is not valid” in LINQ when DateTime field is null

后端 未结 2 582
走了就别回头了
走了就别回头了 2021-01-23 19:59

I got a problem. This my code use a LINQ.

var resultCases = from row2 in dtCases.AsEnumerable()
                  where row2.Field(\"caseID\") == case         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-23 20:45

    Update: try this

    public static class ConversionExtensions
    {
        public static string SafeDateTime(this object value)
        {
            if (value == DBNull.Value) return string.Empty;
    
            var valueType = value.GetType();
            if (typeof (DateTime?).IsAssignableFrom(valueType))
            {
                var nullableValue = value as DateTime?;
                if (nullableValue == null) return string.Empty;
                return nullableValue.Value.ToString();
            }
            if (typeof (DateTime).IsAssignableFrom(valueType))
            {
                return ((DateTime) value).ToString();
            }
            return string.Empty;
        }
    }
    

    Called with:

    effectiveDate = row2["caseEffectiveDate"].SafeDateTime()
    

提交回复
热议问题