SELECT @@DBTS using Linq to SQL

2020-04-13 17:33发布

How can I use Linq to SQL to retrieve @@DBTS using C#?

Here is what I am trying:

IEnumerable<System.Data.Linq.Binary> results = db.ExecuteQuery<System.Data.Linq.Binary>(@"SELECT @@DBTS");

However, this results in "The type 'System.Data.Linq.Binary' must declare a default (parameterless) constructor in order to be constructed during mapping."

If I try to use byte[], I get the same error but with byte[] instead of System.Data.Linq.Binary.

3条回答
爷的心禁止访问
2楼-- · 2020-04-13 17:55

And an even simpler syntax when using EF5+ and DbContext:

public long CurrentRowVersion()
{
  return Database.SqlQuery<long>("select convert(bigint, @@DBTS)").First();
}
查看更多
Luminary・发光体
3楼-- · 2020-04-13 18:01

I suspect you might have to use regular ADO.NET and ExecuteReader/ExecuteScalar...

using(SqlConnection conn = new SqlConnection(CONN_STRING))
using(SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "SELECT @@DBTS";
    cmd.CommandType = CommandType.Text;
    conn.Open();
    byte[] ts = (byte[]) cmd.ExecuteScalar();
    foreach (byte b in ts)
    {
        Console.Write(b.ToString("X2"));
    }
    Console.WriteLine();
}
查看更多
放我归山
4楼-- · 2020-04-13 18:09

I found another way to do this using Linq to SQL alone:

        IEnumerable<Int64> results =
            db.ExecuteQuery<Int64>(@"SELECT CONVERT(bigint,@@DBTS)");
        Int64 latestver = results.First();
查看更多
登录 后发表回答