问题描述
我目前正在使用Entity Framework 4.1和MySQL开发应用程序.我想使用开放式并发,因此需要创建一个表结构,以允许EF检测并发问题.我的目标与此类似: http://blogs.msdn.com/b/alexj/archive/2009/05/20/tip-19-how-to-use-optimistic-concurrency -in-the-entity-framework.aspx .
I'm currently developing an app using Entity Framework 4.1 and MySQL. I want to use optimistic concurrency and therefore need to create a table structure which allows EF to detect concurrency issues. My goal is something similar to this: http://blogs.msdn.com/b/alexj/archive/2009/05/20/tip-19-how-to-use-optimistic-concurrency-in-the-entity-framework.aspx.
我的问题是,与MS SQL Server相比,MySQL中的时间戳类型不同.除此之外,时间戳和日期时间都无法在MySQL中提供亚秒级精度(http://feedblog.org/2007/05/26/why-doesnt-mysql-support-millisecond-datetime-resolution/).因此,这些类型在检测并发问题方面将非常不利.
My problem is that the timestamp-type is different in MySQL compared to MS SQL Server. In addition to that neither timestamp nor datetime offer sub-second precision in MySQL (http://feedblog.org/2007/05/26/why-doesnt-mysql-support-millisecond-datetime-resolution/). These types would therefore be quite bad in detecting concurrency-problems.
我还可以使用其他什么数据类型来解决此问题?我当时在考虑使用Guid.但是,这种方法存在两个潜在的问题:1. MySQL将Guid存储为char(36),使其效率非常低下. 2.我不确定EF是否要求严格增加行版本,或者是否足以保证行的唯一性.
What other data-type could I use to solve this? I was thinking of maybe using a Guid. There are two potential problems with this approach though: 1. MySQL stores Guids as char(36) making them very inefficient. 2. I'm not sure if the EF requires the row-version to be strictly increasing or if it's enough that it's unique.
推荐答案
重要警告: 未测试 -只是大声思考.
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.
这篇关于实体框架和MySQL的乐观并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!