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

灰太狼的梦想

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

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

原文链接: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列,用于并发检查。
一个实体只能有一个时间戳列,我们看看下面的图:
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
posted @ 2019-04-09 17:58  灰太狼的梦想  阅读(1490)  评论(0编辑  收藏  举报