且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架和MySQL的乐观并发

更新时间:2023-02-20 12:18:26

重要警告: 未测试 -只是大声思考.

Big caveat: NOT TESTED - just thinking aloud.

EF支持覆盖 SaveChanges 是定义一个接口,例如:

EF supports override of SaveChanges, so perhaps one option is to define an interface such as:

interface IVersionedRow {
    int RowVersion {get;set;}
}

并将int RowVersion属性/字段添加到模型类和数据库表中,并使用partial class来实现此接口(使用隐式接口实现):

and add an int RowVersion property/field to both your model class(es) and the database table(s), and use partial class to implement this interface (using implicit interface implementation):

partial class Customer : IVersionedRow {}
partial class Order : IVersionedRow {}
...

然后覆盖SaveChanges,类似:

public override int SaveChanges(SaveOptions options)
{    
    foreach (ObjectStateEntry entry in
        ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
    {
        var v = entry.Entity as IVersionedRow;
        if(v != null) v.RowVersion++;
    }
    return base.SaveChanges(options);
}

然后应该用作手动实现的行版本计数器(理论上未经测试).将RowVersion的变更验证保持启用状态,这应该起作用.

that should then function (in theory - untested) as a manually implemented row-version counter. Leave change-validation enabled for RowVersion, and that should serve.