使用多个DbContexts及其自己的事务范围

时间:2012-07-19 21:05:07

标签: c# sql-server entity-framework-4 transactions

我需要同时从两个不同的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():
    }
}

1 个答案:

答案 0 :(得分:0)

您是否尝试在连接字符串中设置enlist = false?

http://forums.asp.net/t/1401606.aspx/1

Brgrds, 拉里