SELECT @@DBTS using Linq to SQL

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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();
}

Method 2

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();

Method 3

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

public long CurrentRowVersion()
{
  return Database.SqlQuery<long>("select convert(bigint, @@DBTS)").First();
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x