none
Exception caused by Sql2008Provider, Can I force Linq to Sql to use Sql2005Provider

    Question

  • This query (or rather one similar to it) is in a codebase we have already deployed.

    var timeblocks = from tb in DB.TimeBlocks
                                  where tb.StartDate.Date.AddDays(1) <= DateTime.Today
                                  select tb.Id;

    DB is a datacontext that connects to the database.  TimeBlocks is a fairly simple table, StartDate is a DateTime column.

    Currently the database is hosted on a Sql Server 2005 Installation, but we are in the process of upgrading to a Sql Server 2008 Installation.

    The query currently exectutes without problems.

    If we change the connection string to point at a copy of the same database running on Sql Server 2008 (with the compatability level set for 2005) the query fails with the SqlException:

    "The datepart millisecond is not supported by date function dateadd for data type date."

    This seems to be due to the different sql emitted by Linq to SQL when it  connects to the 2008db (I assume this is because it uses Sql2008Provider instead of the Sql2005Provider). 

    The 2005 Provider produces good SQL:

    "{SELECT [t0].[Id]
    FROM [dbo].[TimeBlock] AS [t0]
    WHERE DATEADD(ms, (CONVERT(BigInt,@p0 * 86400000)) % 86400000, DATEADD(day, (CONVERT(BigInt,@p0 * 86400000)) / 86400000, DATEADD(HOUR, -DATEPART(HOUR, [t0].[StartDate]), DATEADD(MINUTE, -DATEPART(MINUTE, [t0].[StartDate]), DATEADD(SECOND, -DATEPART(SECOND, [t0].[StartDate]), DATEADD(MILLISECOND, -DATEPART(MILLISECOND, [t0].[StartDate]), [t0].[StartDate])))))) <= @p1
    }" 

    which successfully executes the query.  However the sql emitted by the Sql2008Provider:
    "
    {SELECT [t0].[Id]
    FROM [dbo].[TimeBlock] AS [t0]
    WHERE DATEADD(ms, (CONVERT(BigInt,@p0 * 86400000)) % 86400000, DATEADD(day, (CONVERT(BigInt,@p0 * 86400000)) / 86400000, CONVERT(DATE, [t0].[StartDate]))) <= @p1
    }"

    Contains the erroneous sql that causes the exception.

    Am I right in thinking that the it is the Sql provider that is causing this problem? 

    Is there a way we can get round this problem by forcing the DataContext to use the Sql2005Provider for this db?

    Thanks for any help you can give us!

    - Neil
    Friday, February 26, 2010 12:15 AM

All replies

  • Looks like MS has documented this as a bug, to be fixed in .net 4 (https://connect.microsoft.com/VisualStudio/feedback/details/366011/linq-to-sql-query-translator-produces-syntactically-incorrect-t-sql-from-datetime-date-method)

    I have the same problem. Have you found a workaround?

    Wednesday, March 10, 2010 5:29 PM

  • Have you solved the problem? I'm still concerned about it.
    Thursday, January 20, 2011 3:07 AM