2016-09-09 39 views
0

隨着這些問題的線路:EF代碼第一次預過濾器日期時間/更新

  1. 'datetime2' error when using entity framework in VS 2010 .net 4.0
  2. How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

我試圖先用代碼來生成基於數據庫在我不擁有的型號上。 I.E.我無法修改模型。 (我正在使用服務器應用程序加速桌面應用程序。)

我知道在轉換爲SqlDateTime時,C#中的DateTime值具有無效的MinDate。此外,從實體框架創建的SQL Express實例不支持datetime2。我試圖應用過濾器使用默認值的約定:

this.Properties<DateTime>() 
       .Configure(o => o.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed).HasColumnAnnotation("SqlDefaultValue", "GETDATE()")); 

然而,當我這樣做,我得到的錯誤Cannot insert the value NULL into column 'CreatedDate', table 'blahblahblah.Companies'; column does not allow nulls. INSERT fails.

我不知道我的理解是錯誤消息作爲值從不爲空。但我猜,因爲DatabaseGeneratedOptioncomputed,值沒有被設置。

到目前爲止,這些選項都不適用於日期時間。如果有預過濾插入和更新的方法,我可以對日期時間值運行檢查並將其值設置爲SqlDateTime最小值。不過,我的Google foo沒有返回任何此類操作的結果。如果沒有辦法做到這一點,我可以做一個幫助函數,使用反射來自動調整所有的日期時間對象。

回答

0

我寫了一個輔助函數來預先更新日期時間值。

public static class DateTimeSwitch 
{ 
    public static void DateTimeToSqlDateTime(this object obj) 
    { 
     Type objType = obj.GetType(); 

     if (typeof(IEnumerable).IsAssignableFrom(objType)) 
     { 
      IEnumerable enumerable = (IEnumerable)obj; 
      if (enumerable != null) 
      { 
       foreach (object c in enumerable) 
       { 
        if (c != null) 
         c.DateTimeToSqlDateTime(); 
       } 
      } 
     } 
     else 
     { 
      PropertyInfo[] properties = objType.GetProperties(); 

      foreach (PropertyInfo property in properties) 
      { 
       if (typeof(DateTime).IsAssignableFrom(property.PropertyType)) 
       { 
        // Get the value, adjust it. 
        DateTime value = (DateTime)property.GetValue(obj, null); 
        if (value < (DateTime)SqlDateTime.MinValue) 
        { 
         property.SetValue(obj, (DateTime)SqlDateTime.MinValue, null); 
        } 
       } 
       else if (!property.PropertyType.IsPrimitive && typeof(String) != property.PropertyType && typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) 
       { 
        IEnumerable enumerable = (IEnumerable)property.GetValue(obj, null); 
        if (enumerable != null) 
        { 
         foreach (object c in enumerable) 
         { 
          if (c != null) 
           c.DateTimeToSqlDateTime(); 
         } 
        } 
       } 
       else if (!property.PropertyType.IsPrimitive) 
       { 
        if (property.PropertyType.Assembly == objType.Assembly) 
        { 
         var value = property.GetValue(obj, null); 
         if (value != null) value.DateTimeToSqlDateTime(); 
        } 
       } 
      } 
     } 
    } 
}