在客户端应用程序中,我需要将表的所有数据都存储在内存中。我经常从数据库中重新读取数据以确保我拥有最新的数据。为避免每次使用 RowVersion/Timestamp 列时都读取所有数据以仅获取更改的数据:
SELECT ... WHERE CAST(RowVersion AS BIGINT) > @lastReadMaxRowVersion
如何在 Linq2Sql 中执行此操作?如果我将 dbml 中的服务器数据类型更改为 BIGINT,我将收到 InvalidCastException。
最佳答案
您应该能够通过对 System.Data.Linq.Binary 进行比较来做类似的事情在 .NET 中表示 RowVersion/Timestamp 值的对象。
除非,您真的不会比较任何东西。诀窍是编写一个 LINQ 查询,该查询将被转换为执行实际比较的 T-SQL
。
通过使用一个名为 Compare
的方法,该方法接受 2 个 Binary
参数,LINQ 将愉快地生成一些 T-SQL
来比较 rowversion 字段数据库。它不会调用实际方法。它只是用来让它生成所需的 SQL。
不是将最新读取的 rowversion 值存储为 Int64
,而是将其存储为 Binary
。
private Binary _latestRowVersion = new Binary(new byte[] { 0 });
private void Read()
{
using (var ctx = new DataContext())
{
var all =
(from c in ctx.Categories
where c.RowVersion.Compare(_latestRowVersion) > 0
select c).ToList();
if (all.Any())
{
_latestRowVersion =
all.OrderByDescending(
p => BitConverter.ToInt64(p.RowVersion.ToArray(), 0))
.First()
.RowVersion;
}
}
}
public static class BinaryComparer
{
public static int Compare(this Binary item1, Binary item2)
{
throw new NotImplementedException();
}
}
关于c# - Linq-to-2sql - 选择更改的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17106282/