每天学一点,每天积累一点,进步就不止一点点!PS:好记性不如烂笔头,学会总结,学会思考~~~ ----要飞翔,必须靠自己!

灰太狼的梦想

好记性不如烂笔头,学会总结,学会思考~~~

9.12 翻译系列:数据注解特性之ConcurrencyCheck【EF 6 Code-First系列】

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

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

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

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特性可以用在任何数据类型的的任何数量的属性上面。

posted @ 2019-04-10 10:32  灰太狼的梦想  阅读(1434)  评论(0编辑  收藏  举报