'datetime2' error when using entity framework in VS 2010 .net 4.0 'datetime2' error when using entity framework in VS 2010 .net 4.0 sql-server sql-server

'datetime2' error when using entity framework in VS 2010 .net 4.0


Entity framework handles all the dates as a Datetime2, so, if your fields in the database are Datetime, this could be a problem.We had the same problem here, and from what we found, populating all the date fields and changing the datatype, are the most commom solutions


If you are using Code First you must declare any optional DateTime property as DateTime? or Nullable<DateTime>. Unset DateTime objects can cause issues.

If the property is nullable in the database and a standard DateTime in code (not DateTime?), ADO.NET will send an insert command with a date of 0001-01-01 (not NULL), but the minimum SQL DateTime value is 1753-01-01, causing an error. If your DateTime property in the code is nullable (e.g. DateTime? or Nullable<DateTime>), the insert command is will attempt to insert a NULL instead of an out-of-range date.


Use that SQL script to convert all the columns from datetime to datetime2. It skips all the tables contains 'aspnet' for your convenience.

DECLARE @SQL AS NVARCHAR(1024)DECLARE @TBL AS NVARCHAR(255)DECLARE @COL AS NVARCHAR(255)DECLARE @NUL AS BITDECLARE CUR CURSOR FAST_FORWARD FOR    SELECT  SCHEMA_NAME(t.schema_id)+'.'+t.name, c.name, c.is_nullable    FROM    sys.tables AS t    JOIN    sys.columns c ON t.object_id = c.object_id    JOIN    information_schema.columns i ON i.TABLE_NAME = t.name                                         AND i.COLUMN_NAME = c.name    WHERE   i.data_type = 'datetime' and t.name not like '%aspnet%'    ORDER BY t.name, c.nameOPEN CURFETCH NEXT FROM CUR INTO @TBL, @COL, @NULWHILE @@FETCH_STATUS = 0BEGIN    SELECT @SQL = 'ALTER TABLE ' + @TBL         + ' ALTER COLUMN [' + @COL + '] datetime2'         + (CASE WHEN @NUL=1 THEN '' ELSE ' NOT' END) + ' NULL;'    EXEC sp_executesql @SQL    FETCH NEXT FROM CUR INTO @TBL, @COL, @NULENDCLOSE CUR;DEALLOCATE CUR;

It works for me!