我需要同时从两个不同的DbContexts访问数据,确保每个人使用READ UNCOMMITTED进行查询(真的,重要的是它不会锁定它迭代的行 - 添加WITH对查询没有锁定也会起作用)。
如何使用Entity Framework执行此操作?如果我在TransactionScope中包装两个查询中的每一个,它会尝试将事务提升为MSDTC,这对我们来说不是一个选项。
private static IEnumerable<Image> EnumerateSourceImages()
{
using (var dbContext = new SourceDbContext())
{
using (var transScope = new TransactionScope(
TransactionScopeOption.RequiresNew,
new TransactionOptions() {
IsolationLevel = IsolationLevel.ReadUncommitted
}
)
)
{
var imagesSourceQuery = dbContext.ImageDatas
.AsNoTracking()
.OrderBy(imageData => imageData.ImageID)
foreach (var image in imagesSourceQuery)
{
yield return image;
}
transScope.Complete();
}
}
}
private static IEnumerable<Image> EnumerateDestinationImages()
{
using (var dbContext = new DestinationDbContext())
{
using (var transScope = new TransactionScope(
TransactionScopeOption.RequiresNew,
new TransactionOptions() {
IsolationLevel = IsolationLevel.ReadUncommitted
}
)
)
{
var imagesSourceQuery = dbContext.ImageDatas
.AsNoTracking()
.OrderBy(imageData => imageData.ImageID)
foreach (var image in imagesSourceQuery)
{
yield return image;
}
transScope.Complete();
}
}
}
private static void main(string[] args){
{
IEnumerator<ItemImage> sourceImagesEnumerator = null;
IEnumerator<ItemImage> destImagesEnumerator = null;
try{
sourceImagesEnumerator = EnumerateSourceImages().GetEnumerator();
destImagesEnumerator = EnumerateDestinationImages().GetEnumerator();
bool sourceHasMore = sourceImagesEnumerator.MoveNext();
//Exception on next line about MSDTC Promotion
bool destHasMore = destImagesEnumerator.MoveNext();
} finally{
if(sourceImagesEnumerator != null) sourceImagesEnumerator.Dispose();
if(destImagesEnumerator != null) destImagesEnumerator.Dispose():
}
}