Entity Framework,TransactionScope 混合使用的問題討論

using (var ts = new TransactionScope())
{
    string connStr = "Data Source=.;Initial Catalog=Test;Integrated Security=true;";
    using (SqlConnection connection = new SqlConnection(connStr))
    {
        // Create the command and set its properties.
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandText = "InsertMessage";
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@ID", 1));
        command.Parameters.Add(new SqlParameter("@Message", "dfd"));
        connection.Open();
        command.ExecuteNonQuery();
        connection.Close();
        using (var context = new Entities())
        {
            context.Message.Add(new Message { ID = 222, Msg = "dfdfd" });
            context.SaveChanges();
        }
    }
    ts.Complete();
}

會報錯,除非你打開MSDTS這個windows service
緣由是:If you use a single connection within a TransactionScope, it will be done as a local transaction (handled within that connection). If multiple db connections are involved, it will be escalated to a distributed transaction which requires that MSDTC is running on both the machine where your code runs and on the DB server, and that MSDTC on the client has permissions to communicate with MSDTC on the server (http://www.datazx.cn/Forums/en-US/0a365486-c57a-4ee9-a59f-e90a4a4abfbf/action?forum=adodotnetentityframework)windows

EntityFramework5有一個辦法能夠解決這個問題ui

using (var context = new Entities())
{
    context.Database.Connection.ConnectionString = connStr;     context.Message.Add(new Message { ID = 222, Msg = "dfdfd" });
    context.SaveChanges();
}

如下版本暫時沒找到好的辦法,你們有什麼方法嗎?spa

相關文章
相關標籤/搜索