TransactionFlowOption有三个选项:
一为NotAllowed,这代表了禁止客户端传播事务流到服务端,即使客户端启动了事务,该事务也会被忽略;
二为Allowed,这代表允许客户端的事务传播到服务端,但服务器端不一定会引用到此事务;
三为Mandatory,这代表服务端与客户端必须同时启动事务流,否则就会抛出InvalidOperationException异常。
[ServiceContract(SessionMode=SessionMode.Required)]
public interface IOrdersService
{
[OperationContract]
[TransactionFlow(TransactionFlowOption.Mandatory)]
string PlaceOrder(Order order);
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession, TransactionAutoCompleteOnSessionClose=true)]
public class OrdersService : IOrdersService
[OperationBehavior(TransactionScopeRequired=true,
TransactionAutoComplete=false)]
public string PlaceOrder(Order order)
{
using (var conn = new SqlConnection(connString))
{
var cmd = new SqlCommand("Insert Orders (CustomerId) Values( @customerId)", conn);
cmd.Parameters.Add(new SqlParameter("@customerId", order.CustomerId));
try
{
conn.Open();
if (cmd.ExecuteNonQuery() <= 0)
{
return "The order was not placed";
}
cmd = new SqlCommand("Select Max(OrderId) From Orders Where CustomerId = @customerId", conn);
cmd.Parameters.Add(new SqlParameter("@customerId", order.CustomerId));
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
orderId = Convert.ToInt32(reader[0].ToString());
}
}
return string.Format("Order {0} was placed", orderId);
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}
}
[OperationBehavior(TransactionScopeRequired = true,
TransactionAutoComplete = false)]
public string AdjustInventory(int productId, int quantity)
{
using (var conn = new SqlConnection(connString))
{
var cmd = new SqlCommand("Update Products Set OnHand = 1 Where ProductId = @productId", conn);
cmd.Parameters.Add(new SqlParameter("@quantity", quantity));
try
{
conn.Open();
if (cmd.ExecuteNonQuery() <= 0)
{
return "The inventory was not updated";
}
else
{
return "The inventory was updated";
}
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}
}
----------------------client---------------------------
using (var tranScope = new TransactionScope())
{
proxy = new OrdersServiceClient("WSHttpBinding_IOrdersService");
{
try
{
result = proxy.PlaceOrder(order);
tranScope.Commit();
}
catch (FaultException faultEx)
{
}
}