问题
In response to another question on stackoverflow RavenDB does not play nicely with Transaction Scope i have created a test case where i isolate my transactions for storing and reading. In my test case i am making a call to a raven document store and a mssql database within the same transaction. But i get a Web Exception. Any ideas why or how to solve it. Below is my code
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;
}
}
}
I am well aware that i start with a transaction scope and then i don't complete it, it's what i am testing. Not completing a transaction should roll it back, if i'm right. I want to test a failed transaction, and then a successful one.
And the reason why i'm calling ravendb and mssql inside the same transaction here is because i am simulating what might happen with nested transactions where one call might be to sql and another to raven, without knowing the other call was even made.
来源:https://stackoverflow.com/questions/24828095/ravendb-and-mssql-inside-same-transaction-scope-results-in-webexception