原文链接:https://www.entityframeworktutorial.net/code-first/TimeStamp-dataannotations-attribute-in-code-first.aspx

EF 6 Code-First系列文章目录:

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

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数据类型:
9.11 翻译系列:数据注解特性之--Timestamp【EF 6 Code-First系列】

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

相关文章:

  • 2022-01-27
  • 2021-12-26
  • 2021-11-23
  • 2021-10-13
  • 2019-03-31
  • 2021-09-14
  • 2019-03-31
  • 2022-03-09
猜你喜欢
  • 2021-05-23
  • 2021-11-21
  • 2022-01-23
  • 2021-08-31
  • 2021-11-20
  • 2022-01-13
  • 2021-05-30
相关资源
相似解决方案