views:

46

answers:

2

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?

A: 

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.

James Curran
Changes.Date has server data type `DateTime2 NOT NULL`.
TN
The problem might be caused that it is going to `SqlMethods.DateDiffNanosecond` not directly to Changes.Date...
TN
A: 

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);
David B
Is there any clever way to lookup a specific parameter on a dynamic query (not known in advance)? Or, I have to replace all `datetime` with `datetime2`?
TN