如何强制 LINQ to SQL 将 .NET DateTime 作为 datetime2 传递?

发布于 2024-09-09 06:39:57 字数 824 浏览 5 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

貪欢 2024-09-16 06:39:57

打开 .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.

甜中书 2024-09-16 06:39:57

如果你不介意打开引擎盖,你可以这样做:

DbCommand dbCommand = dataContext.GetCommand(query);

dbCommand.Parameters ...

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

DbDataReader reader = command.ExecuteReader();

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文