How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

前端 未结 15 903
-上瘾入骨i
-上瘾入骨i 2020-12-07 19:39

I\'m using the DbContext and Code First APIs introduced with Entity Framework 4.1.

The data model uses basic data types such as string

15条回答
  •  半阙折子戏
    2020-12-07 20:24

    In some cases, DateTime.MinValue (or equivalenly, default(DateTime)) is used to indicate an unknown value.

    This simple extension method can help handle such situations:

    public static class DbDateHelper
    {
        /// 
        /// Replaces any date before 01.01.1753 with a Nullable of 
        /// DateTime with a value of null.
        /// 
        /// Date to check
        /// Input date if valid in the DB, or Null if date is 
        /// too early to be DB compatible.
        public static DateTime? ToNullIfTooEarlyForDb(this DateTime date)
        {
            return (date >= (DateTime) SqlDateTime.MinValue) ? date : (DateTime?)null;
        }
    }
    

    Usage:

     DateTime? dateToPassOnToDb = tooEarlyDate.ToNullIfTooEarlyForDb();
    

提交回复
热议问题