【发布时间】:2012-05-03 11:38:46
【问题描述】:
我用过这个向导:http://www.c-sharpcorner.com/uploadfile/shivprasadk/wcf-faq-part-5-transactions/ 为什么不回滚??我不明白!
我有一个服务和客户端应用程序,但我不知道这段代码有什么问题。 在完美地完成这一行并将其保存在我的数据库中之后,
proxy.AddEmployee("Stav", "20");
下一行抛出异常,因为我没有向 Age 参数发送数字,但事务没有回滚第一行,所以信息:Stav,20 仍然存在于我的数据库中!
proxy.AddEmployee("Stav123", "Not a Number(-->will do Exception)")
编辑 1: 我添加了 AddEmployee 实现。
客户:
static void Main(string[] args)
{
ServiceReference1.IJob proxy = new ServiceReference1.JobClient();
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
{
try
{
proxy.AddEmployee("Stav", "20");
proxy.AddEmployee("Stav123", "Not a Number(-->will do Exception) ");//stop the running and show the Exception but keep the stav,20 in DB
ts.Complete();
}
catch
{
ts.Dispose();
}
}
}
服务:
[ServiceContract]
public interface IJob
{
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
void AddEmployee(string Name, string Age);
}
public class JobImplement:IJob
{
[OperationBehavior(TransactionScopeRequired = true)]
public void AddEmployee(string Name, string Age)
{
string strConnection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\stavalfi\Desktop\WCF2\ConsoleApplication4\WCF_DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection objConnection = new SqlConnection(strConnection);
objConnection.Open();
SqlCommand objCommand = new SqlCommand("INSERT INTO Employee (Name,Age) " + "VALUES ('" + Name + "' ,'" + Age + "')", objConnection);
objCommand.ExecuteNonQuery();
objConnection.Close();
}
}
static void Main(string[] args)
{
WSHttpBinding Basic = new WSHttpBinding();
Basic.TransactionFlow = true;
ServiceHost host = new ServiceHost(typeof(JobImplement), new Uri("http://localhost:8080"));
//
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(behavior);
//
host.AddServiceEndpoint(typeof(IJob), new BasicHttpBinding(), "Request123");
host.Open();
//
Console.WriteLine("opened");
Console.ReadLine();
//
host.Close();
}
【问题讨论】:
-
添加 AddEmployee 方法是如何实现的?它真的兑现了交易吗?
-
我用工具更新了话题。还有什么?
-
您使用的是什么绑定?并非所有绑定都支持事务。
-
好的,支持事务。您在 app.config trasactionFlow = "ture" 的 System.ServiceModel 绑定部分中有吗?又名。
-
我在我的代码中写了它。所以不需要cofing。我会将连接添加到我的主题。
标签: c# transactions transactionscope distributed-transactions