[EntityFramework]记录Linq中如何比较数据库中Timestamp列的方法(如大于0x00000000000007D1的记录)

Timestamp对于EF实体的类型是byte[]
class Program
    {
        static void Main(string[] args)
        {
            using (var context = new DbContext())
            {
                var val = BitConverter.GetBytes(0x00000000000007D1).Reverse().ToArray();
                var byteArr = Enumerable.Range(0, 8 - val.Length)
                    .Select(c => (byte)0)
                    .Concat(val).ToArray();
                //使用扩展方法,查询大于0x00000000000007D1的记录
                var query = context.TestTable
                    .Where(c => c.RowVersion.Compare(byteArr) > 0)
                    .ToList();
            }
        }
    }
    static class ArrayExtensions
    {
        public static int Compare(this byte[] b1, byte[] b2)
        {
            if (b1 == null && b2 == null)
                return 0;
            else if (b1 == null)
                return -1;
            else if (b2 == null)
                return 1;
            return ((IStructuralComparable)b1).CompareTo(b2, Comparer<byte>.Default);
        }
    }
    public class TestTable
    {
        [Key]
        public int id { get; set; }

        [Timestamp]
        public byte[] RowVersion { get; set; }
    }

 生成的sql如下

exec sp_executesql N'SELECT 
    [Extent1].[id] AS [id], 
    [Extent1].[RowVersion] AS [RowVersion]
    FROM [dbo].[TestTable] AS [Extent1]
    WHERE [Extent1].[RowVersion] > @p__linq__0',N'@p__linq__0 varbinary(8000)',@p__linq__0=0x00000000000007D1

 

  

posted @ 2018-01-30 18:37  菜刀和板砖  阅读(340)  评论(0编辑  收藏  举报