2016-09-09 40 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(); 
        } 
       } 
      } 
     } 
    } 
}