随着这些问题的线路:EF代码第一次预过滤器日期时间/更新
- 'datetime2' error when using entity framework in VS 2010 .net 4.0
- 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.
我不知道我的理解是错误消息作为值从不为空。但我猜,因为DatabaseGeneratedOption
是computed
,值没有被设置。
到目前为止,这些选项都不适用于日期时间。如果有预过滤插入和更新的方法,我可以对日期时间值运行检查并将其值设置为SqlDateTime最小值。不过,我的Google foo没有返回任何此类操作的结果。如果没有办法做到这一点,我可以做一个帮助函数,使用反射来自动调整所有的日期时间对象。