开发者

how to handle null date in c# for mysql without convert them to null

开发者 https://www.devze.com 2023-01-25 06:00 出处:网络
0000-00-00 00:00:00 i have this date in mysql as default date in undefined case how i can get them in c# and re insert them without changes in MysqlDatabase.
0000-00-00 00:00:00

i have this date in mysql as default date in undefined case

how i can get them in c# and re insert them without changes in MysqlDatabase.

if i get them in c#. i got error that Unable to convert MySQL date/time value to System.DateTime

how i can get this in c# and insert them witho开发者_如何学编程ut any changes in date


Use Nullable types and the as operator to represent your datetime values in C#. This is the easiest mechanism to deal with database types which map to value types and potentially have no value. For example:

object valueFromMySQL = GetValueFromMySQL(); // or whatever
DateTime? datetimeValue = valueFromMySQL as DateTime?;

If the value is valid, it will be interpreted as DateTime, otherwise it will be interpreted as null.

You should also be able to send values of the type DateTime? back to MySQL without issue.


DateTime.MinValue (the minimum value DateTime supports) is 1-1-0001 0:00:00. Is it an option to set your MySQL default that date date/time instead of 0-0-0000 0:00:00? The problem here is that the date/time you've set as your default is not a valid date/time (there is no month with the number zero), so DateTime will never accept this date.


You will need to use the try parse in this case.

DateTime ReturnedDateValue;

DateTime DateFromSqlDB = EntityClass.DateCreated;

if (DateTime.TryParse(DateFromSqlDB, ReturnedDateValue))
{
    /// Do the insert stuff here
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号