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

在EF 6和EF Core中,ConcurrencyCheck可以应用于实体的一个或者多个属性上面。当属性被标识了这个特性,在生成的数据表中的相应的列,就会用来做乐观检查.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
using System.ComponentModel.DataAnnotations;

public class Student
{
    public int StudentId { get; set; }
     
    [ConcurrencyCheck]
    public string StudentName { get; set; }
}

在上面的例子中,ConcurrencyCheck特性应用在Student实体的StudentName属性上,所以EF将会在更新的时候,包含StudentName列,用于乐观检查,看看下面的例子:

using(var context = new SchoolContext()) 
{
    var std = new Student()
    {
        StudentName = "Bill"
    };

    context.Students.Add(std);
    context.SaveChanges();

    std.StudentName = "Steve";
    context.SaveChanges();
}

上面的代码例子,将会在更新的时候,生成这样的语句【Where条件中】:

exec sp_executesql N'UPDATE [dbo].[Students]
SET [StudentName] = @0
WHERE (([StudentId] = @1) AND ([StudentName] = @2))
',N'@0 nvarchar(max) ,@1 int,@2 nvarchar(max) ',@0=N'Steve',@1=1,@2=N'Bill' go 

请注意:Timestamp特性只能用在单独的byte数组属性上,而ConcurrencyCheck特性可以用在任何数据类型的的任何数量的属性上面。

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄