博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何管理Entity Framework中得事务
阅读量:5149 次
发布时间:2019-06-13

本文共 5921 字,大约阅读时间需要 19 分钟。

http://msdn.microsoft.com/en-us/library/bb738523.aspx

 This topic provides an example of how to define a transaction that coordinates making changes to objects in an object context with other external operations. For more information, see .

The example in this topic is based on the . To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedure in . You must also have Microsoft Windows Message Queuing installed.

Example

This example defines a . The TransactionScope ensures that changes to objects in the object context are coordinated with a message queue. The Entity Framework uses this transaction when it saves changes to the database. When an  occurs, the operation is retried up to two times. When the operation succeeds, the changes in the object context are accepted. For more information, see .

This example uses a long-running object context, which is disposed after the transaction succeeds or after all retries have been attempted.

C#
using System; using System.Linq; using System.Data; using System.Data.Objects; using System.Messaging; using System.Transactions;  namespace ObjectServicesConceptsCS {     class TransactionSample     {         public static void EnlistTransaction()         {             int retries = 3;             string queueName = @".\Fulfilling";              // Define variables that we need to add an item.             short quantity = 2;             int productId = 750;             int orderId = 43680;              // Define a long-running object context.             AdventureWorksEntities context                 = new AdventureWorksEntities();              bool success = false;              // Wrap the operation in a retry loop.             for (int i = 0; i < retries; i++)             {                 // Define a transaction scope for the operations.                 using (TransactionScope transaction = new TransactionScope())                 {                     try                     {                         // Define a query that returns a order by order ID.                         SalesOrderHeader order =                         context.SalesOrderHeaders.Where                         ("it.SalesOrderID = @id", new ObjectParameter(                          "id", orderId)).First();                          // Load items for the order, if not already loaded.                         if (!order.SalesOrderDetails.IsLoaded)                         {                             order.SalesOrderDetails.Load();                         }                          // Load the customer, if not already loaded.                         if (!order.ContactReference.IsLoaded)                         {                             order.ContactReference.Load();                         }                          // Create a new item for an existing order.                         SalesOrderDetail newItem = SalesOrderDetail.CreateSalesOrderDetail(                             0, 0, quantity, productId, 1, 0, 0, 0, Guid.NewGuid(), DateTime.Today);                          // Add new item to the order.                         order.SalesOrderDetails.Add(newItem);                          // Save changes pessimistically. This means that changes                          // must be accepted manually once the transaction succeeds.                         context.SaveChanges(SaveOptions.DetectChangesBeforeSave);                          // Create the message queue if it does not already exist.                         if (!MessageQueue.Exists(queueName))                         {                             MessageQueue.Create(queueName);                         }                          // Initiate fulfilling order by sending a message.                         using (MessageQueue q = new MessageQueue(queueName))                         {                             System.Messaging.Message msg =                                 new System.Messaging.Message(String.Format(                                     "
" + "
" + "
", order.Contact.ContactID, newItem.ProductID, newItem.OrderQty)); // Send the message to the queue. q.Send(msg); } // Mark the transaction as complete. transaction.Complete(); success = true; break; } catch (Exception ex) { // Handle errors and deadlocks here and retry if needed. // Allow an UpdateException to pass through and // retry, otherwise stop the execution. if (ex.GetType() != typeof(UpdateException)) { Console.WriteLine("An error occured. " + "The operation cannot be retried." + ex.Message); break; } // If we get to this point, the operation will be retried. } } } if (success) { // Reset the context since the operation succeeded. context.AcceptAllChanges(); } else { Console.WriteLine("The operation could not be completed in " + retries + " tries."); } // Dispose the object context. context.Dispose(); } } }

转载于:https://www.cnblogs.com/hyl8218/archive/2011/10/11/2206929.html

你可能感兴趣的文章
一些php文件函数
查看>>
std::min error C2059: 语法错误:“::” 的解决方法
查看>>
Opencv保存摄像头视频&&各种编码器下视频文件占用空间对比
查看>>
「图形学」直线扫描——Bresenham算法改进了中点Bresenham算法?
查看>>
jQuery 给div绑定单击事件
查看>>
Exceptionless 生产部署笔记
查看>>
有关快速幂取模
查看>>
转 ObjExporter Unity3d导出场景地图寻路
查看>>
Linux运维必备工具
查看>>
Ubuntu配置ssh及vnc
查看>>
C语言进阶——const 和 volatile 分析09
查看>>
字符串的查找删除
查看>>
NOI2018垫底记
查看>>
快速切题 poj 1002 487-3279 按规则处理 模拟 难度:0
查看>>
Codeforces Round #277 (Div. 2)
查看>>
一步步学Mybatis-搭建最简单的开发环境-开篇(1)
查看>>
微信小程序图片上传
查看>>
【更新】智能手机批量添加联系人
查看>>
NYOJ-128前缀式计算
查看>>
centos6.7 配置外网端口映射
查看>>