1

为了回答关于 stackoverflow RavenDB 不能很好地与 Transaction Scope 配合使用的另一个问题,我创建了一个测试用例,在其中我隔离了我的事务以进行存储和读取。在我的测试用例中,我正在同一个事务中调用 raven 文档存储和 mssql 数据库。但我得到一个网络异常。任何想法为什么或如何解决它。下面是我的代码

    private static string con = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestDB;Data Source=.";
    static void Main(string[] args)
    {
        using (var scope = new TransactionScope())
        {
            additemtosql();
        }
        Console.WriteLine((itemSqlCount() == 0));

        using (var mDocumentStore = new DocumentStore())
        {
            mDocumentStore.ParseConnectionString("Url=http://localhost:8081");
            mDocumentStore.Initialize();
            using (var scope = new TransactionScope())
            {
                additemtoravendb(mDocumentStore);

                Console.WriteLine((itemSqlCount() == 0));

                scope.Complete();
            }
            Console.WriteLine(itemRavenCount(mDocumentStore) == 1);
        }

    }
    private static void additemtoravendb(IDocumentStore mDocumentStore)
    {
        using (var session = mDocumentStore.OpenSession())
        {
            var dog = new Dog()
            {
                Age = 10,
                BirthDay = DateTime.Now,
                Breed = "Dalmation",
                Name = "Fluffy"
            };
            session.Store(dog);
            session.SaveChanges();
        }
    }

    private static int itemRavenCount(IDocumentStore mDocumentStore)
    {
        using (var session = mDocumentStore.OpenSession())
        {
            var dogs = session.Query<Dog>().ToList();
            return dogs.Count();
        }
    }
    private static void additemtosql()
    {
        var sql = "INSERT INTO RECORDS_TEXT VALUES (1, 'XX', 'XX') ";
        using (var connection = new SqlConnection(con))
        using (var command = new SqlCommand(sql, connection))
        {
            connection.Open();

            command.ExecuteNonQuery();
            Console.WriteLine((itemSqlCount() == 1));
        }
    }
    private static int itemSqlCount()
    {
        using (var connection = new SqlConnection(con))
        using (var command = new SqlCommand("", connection))
        {
            connection.Open();
            command.CommandText = "SELECT COUNT(*) FROM RECORDS_TEXT";
            using (var reader = command.ExecuteReader())
            {
                reader.Read();
                var count = reader.GetInt32(0);
                return count;
            }
        }
    }

我很清楚我从事务范围开始,然后我没有完成它,这就是我正在测试的。如果我是对的,不完成交易应该回滚。我想测试一个失败的交易,然后是一个成功的交易。

我在这里在同一个事务中调用 ravendb 和 mssql 的原因是因为我正在模拟嵌套事务可能发生的情况,其中一个调用可能是 sql,另一个调用是 raven,甚至不知道另一个调用。

4

0 回答 0