EF6/EFCore Code-First Timestamp SQL Server

EF 6和EF Core都包含TimeStamp数据注解特性。它只能用在实体的byte数组类型的属性上,并且只能用在一个byte数组类型的属性上。然后在数据库中,创建timestamp数据类型的列,在更新语句中,EF API自动使用timestamp列,用于并发检查。
一个实体只能有一个时间戳列,我们看看下面的图:
enter description here
enter description here

using System.ComponentModel.DataAnnotations;

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

在上面的例子中,TimeStamp特性应用于Student实体的byte[]类型的RowVersion属性上,所以,EF 将会给RowVersion创建一个timestamp数据类型:
enter description here

timestamp类型的列,在更新的时候,会包含在where语句中:

 
using(var context = new SchoolContext()) 
{
    var std = new Student()
    {
        StudentName = "Bill"
    };
 
    context.Students.Add(std);
    context.SaveChanges();
 
    std.StudentName = "Steve";
    context.SaveChanges();
}

上面的代码,将会生成下面的语句:

 
exec sp_executesql N'UPDATE [dbo].[Students]
SET [StudentName] = @0
WHERE (([StudentId] = @1) AND ([RowVersion] = @2))
SELECT [RowVersion]
FROM [dbo].[Students]
WHERE @@ROWCOUNT > 0 AND [StudentId] = @1',N'@0 nvarchar(max) ,@1 int,@2 binary(8)',@0=N'Steve',@1=1,@2=0x00000000000007D1
go
原文地址:https://www.cnblogs.com/zhaoshujie/p/12178954.html