The Concurrencycheck attribute can be applied to the properties of the domain class. When EF performs the update operation, Code-first puts the value of the column in the Where Condition statement, which you can use to do concurrency checking with existing columns instead of using separate timestamp columns for concurrency checks.
Look at the following code:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.ComponentModel.DataAnnotations.Schema;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceef2{[Table ("Studentinfo")] Public classStudent {[Key] [Column (Order=1)] Public intStudentKey1 {Get;Set; } [Key] [Column (Order=2)] Public intStudentKey2 {Get;Set; } [Column ("Name", typename="ntext")] [MaxLength ( -)] [Concurrencycheck] Public string Studentname {get; set; } [Notmapped ()] Public int? Age {Get;Set; } Public intStdId {Get;Set; } [ForeignKey ("StdId")] Public VirtualStandard Standard {Get;Set; } 1540644854 Public byte[] RowVersion {Get;Set; } }}
Then let's change the code of the main function test:
usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Entity;usingSystem.Data.Entity.Infrastructure;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceef2{classProgram {Static voidMain (string[] args) {Student StuModel1=NULL; Student StuModel2=NULL; using(vardb =NewDbcontextclass ()) {StuModel1= db. Students.where (s = = S.studentkey1 = =1&& S.studentkey2 = =1). Single (); } using(vardb =NewDbcontextclass ()) {StuModel2= db. Students.where (s = = S.studentkey1 = =1&& S.studentkey2 = =1). Single (); } stumodel1.studentname="Test only for one"; Stumodel2.studentname="Test only for twos"; Try { using(vardb =NewDbcontextclass ()) {db. Entry (STUMODEL1). State=entitystate.modified; Db. SaveChanges (); } } Catch(Dbupdateconcurrencyexception ex) {Console.WriteLine (ex). Message); } Try { using(vardb =NewDbcontextclass ()) {db. Entry (STUMODEL2). State=entitystate.modified; Db. SaveChanges (); } } Catch(Dbupdateconcurrencyexception ex) {Console.WriteLine (ex). Message); } console.readkey (); } }}
Then the error concurrency message is:
EXEC sp_executesql N'UPDATE [dbo]. [Studentinfo]SET [Studentname] = @0, [StdId] = @1WHERE (([StudentKey1]= @2) and ([StudentKey2] = @3) and ([Studentname] = @4))', N'@0nvarchar -),@1 int,@2 int,@3 int,@4nvarchar -)', @0=n'Test only for one', @1=1,@2=1,@3=1,@4=n'Test only for one'
Please note:
Note that TimeStamp attribute can is only is applied to a single byte array property in a class, whereas Concurrency Check attribute can applied to any number of properties with any datatype.
The timestamp attribute can only be used in a single-byte attribute class, but the Concurrencycheck attribute may be used in any number of attributes of any type.
Concurrencycheck characteristics of data annotation features "Code-first series"