sql-server - 从 LINQ to SQL 查询时间戳列

标签 sql-server linq performance

我的表有一个名为“RowVer”的时间戳列,LINQ 将其映射到 System.Data.Linq.Binary 类型。这种数据类型对我来说似乎没什么用,因为(除非我错过了一些东西)我不能做这样的事情:

// Select all records that changed since the last time we inserted/updated.
IEnumerable<UserSession> rows = db.UserSessions.Where
( usr => usr.RowVer > ???? );

因此,我正在寻找的解决方案之一是添加一个名为 RowTrack 的新“计算列”,它在 SQL 中定义如下:

CREATE TABLE UserSession
(
RowVer timestamp NOT NULL,
RowTrack  AS (convert(bigint,[RowVer])),
-- ... other columns ...
)

这允许我像我想要的那样查询数据库:

// Select all records that changed since the last time we inserted/updated.
IEnumerable<UserSession> rows = db.UserSessions.Where
( usr => usr.RowTrack > 123456 );

这是一种不好的做事方式吗?对计算列进行查询的性能如何?有更好的解决方法吗?

此外,我正在针对 Sql Server 2000 进行开发,以实现最终的向后兼容性,但我可以说服老板让 2005 成为最低公分母。

最佳答案

AS Diego Frata概述this post有一个 hack 可以从 LINQ 查询时间戳。

诀窍是定义一个带有两个 System.Data.Linq.Binary 参数的 Compare 方法

public static class BinaryComparer
{
 public static int Compare(this Binary b1, Binary b2)
 {
 throw new NotImplementedException();
 }
}

请注意,该函数不需要实现,只有它的名称(Compare)很重要。

查询将类似于:

Binary lastTimestamp = GetTimeStamp();
var result = from job in c.GetTable<tblJobs>
             where BinaryComparer.Compare(job.TimeStamp, lastTimestamp)>0
             select job;

(在 job.TimeStamp>lastTimestamp 的情况下)

编辑: 请参阅Rory MacLeod's answer如果您需要该方法在 SQL 之外工作,请获取该方法的实现。

关于sql-server - 从 LINQ to SQL 查询时间戳列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/547684/

相关文章:

sql-server - tsql 星期几

arrays - Swift 数组随机插入和删除非常慢

performance - 查询运行速度快,但报告呈现速度慢 : how to debug this?

SQL递归+列连接

c# - 我怎样才能做空?

java - LINQ 的 Java 等价物是什么?

c# - 最新日期的 Lambda 表达式

c# - Linq 编码风格 : inline if

windows - TortoiseSVN 在某些 Windows 配置上非常慢

sql-server - 过滤包含值的字段