Question

I have a simple query in LINQ to SQL:

var id = 23479824;
var date = Changes.Where(ch => ch.Id == id).First().Date;
var diff = Changes.Where(ch => ch.Id == id).Select(ch => SqlMethods.DateDiffNanosecond(date, ch.Date)).First();

The diff variable should be zero, however is not. The generated SQL is following:

DECLARE @p0 DateTime = '2010-07-14 15:05:49.207'
DECLARE @p1 Int = 44633

SELECT TOP (1) [t1].[value]
FROM (
    SELECT DATEDIFF(Nanosecond, @p0, [t0].[Date]) AS [value], [t0].[Id]
    FROM [dbo].[Changes] AS [t0]
    ) AS [t1]
WHERE [t1].[Id] = @p1
GO

I found that it is caused by LINQ to SQL which is passing .NET DateTime type as SQL datetime. However the Date column has SQL type datetime2.

Is it a bug in LINQ to SQL or a feature? How to force LINQ to SQL to pass the input date as datetime2?

Was it helpful?

Solution

If you don't mind popping the hood, you could do this:

DbCommand dbCommand = dataContext.GetCommand(query);

dbCommand.Parameters ...

dbParameter.DbType = System.Data.DbType.DateTime2;

DbDataReader reader = command.ExecuteReader();

IEnumerable<ResultType> result = dataContext
  .Translate<ResultType>(reader);

OTHER TIPS

Open your .dbml file, and select the property (Changes.Date).

Open it's Properties Page (Alt-Enter). There is a "Server Data Type" property which you can change.

Save & Rebuilt.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top