如何强制 LINQ to SQL 将 .NET DateTime 作为 datetime2 传递?
我在 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();
diff
变量应该为零,但事实并非如此。生成的 SQL 如下:
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
我发现这是由 LINQ to SQL 引起的,它将 .NET DateTime
类型作为 SQL datetime
传递。但是,Date
列的 SQL 类型为 datetime2
。
这是 LINQ to SQL 中的错误还是功能?如何强制 LINQ to SQL 将输入日期作为 datetime2
传递?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
打开 .dbml 文件,然后选择属性 (Changes.Date)。
打开其属性页(Alt-Enter)。您可以更改“服务器数据类型”属性。
保存并保存重建。
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.
如果你不介意打开引擎盖,你可以这样做:
If you don't mind popping the hood, you could do this: