我必须将一些数据从 SQL Server 2008 DB 同步到 MySql DB。我正在使用 C# 和 EF 来管理数据。
流程是:从 SQL 服务器读取未同步的行,将条目(通过 EntitiesConverter 类)转换为 MySql 数据库实体,将行添加到 MySql,将 SQL 行标记为已同步(并在两个上下文中保存更改)。
代码:
public static int SyncAttivitaToHiPlan(int start, int? end)
{
var options = new TransactionOptions();
options.IsolationLevel = IsolationLevel.Serializable;
using (var scope = new TransactionScope(TransactionScopeOption.Required, options))
{
//MySql ObjectContext
var hpContext = new hiplanEntities1();
//SQL Server ObjectContext
var otoContext = new OTOCOMMEntities1();
var otoProvider = OtoCommEntitiesProvider.GetInstance();
IEnumerable<Attivita> attivitaEntries;
if (end == null)
attivitaEntries = otoProvider.GetUnsyncedAttivita(start);
else
attivitaEntries = otoProvider.GetUnsyncedAttivita(start, (int)end);
var tvavalavs = new ConcurrentQueue<tvavalav>();
//ObjectContext is not thread-safe
//attivitaEntries.AsParallel().AsOrdered().ForAll((a) => tvavalavs.Enqueue(EntitiesConverter.BuildTvavalavFromAttivita(a)));
foreach (var a in attivitaEntries)
{
tvavalavs.Enqueue(EntitiesConverter.BuildTvavalavFromAttivita(a));
}
foreach (var t in tvavalavs)
{
hpContext.tvavalav.AddObject(t);
}
// attivitaEntries.AsParallel().ForAll((a) => a.Synced = true);
foreach (var a in attivitaEntries)
{
a.Synced = true;
}
hpContext.SaveChanges();
otoContext.SaveChanges();
}
return 0; //TODO: return the number of synced rows.
}
}
当我尝试它时,我得到一个 MySql 连接器异常:“MySQL 连接器/网络当前不支持分布式事务。”
我该如何解决这个问题?有没有办法在单个事务中执行此操作(“虚拟”单打事务,因为我正在使用 2 个不同的数据库)而不会出现该异常?