冲突检测

ConcurrencyCheck 的使用:

顾名思义并发检查;

原理:将冲突检测字段的原值带入到更新where中,生成的Sql形如

update tableName set field1=value1, rowVersion=newRowVersion where id=id and rowVersion=oldRowVersion; 

效果:当两个人同时在更新同一条记录的时候,其中一人将更新失败。

参考代码如下:

1、给字段设置[ConcurrencyCheck]特性,字段理论上可以是任何类型,示例中使用时间

[Table("MemberAmount")]
public class MemberAmount : EntityBase
{
    public MemberAmountCategory Category { get; set; }
    [ForeignKey("MemberId")]
    public virtual Member Member { get; set; }
    public virtual int MemberId { get; set; }
    public decimal Amount { get; set; }
    // 看这里,这里,这里
    [ConcurrencyCheck]
    public DateTime RowVersion { get; set; }
}

2、更新的时候,需要同时更新该字段,这里是RowVersion

public MemberAmount Decrease(MemberAmountCategory category, decimal amount)
{
    var a = GetSingle(category);
    a.Amount -= amount;
    // 看这里,这里,这里
    a.RowVersion = DateTime.Now;
    return a;
}

3、db.SaveChanges(),如果出现冲突,则会提示失败。

Database operation expected to affect 1 row(s) but actually affected 0 row(s). 
Data may have been modified or deleted since entities were loaded. 
See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.