TransactionScope中的多个插入 [英] Multiple Inserts in a TransactionScope

查看:63
本文介绍了TransactionScope中的多个插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是在使用EF的网站上工作。

我有两个表:产品和ItemDetails。产品很简单,它包含产品的ID和名称。 ItemDetails包含一些附加信息,这些信息适用于多种类型的项目,而不是产品。
当我在Products表中创建产品时,我还在ItemDetails中创建了一个关联的记录。因为ItemDetails可以包含与来自其他表的记录相关联的详细信息,所以我不使用Products和ItemDetails表之间的外键关系。

我的要求是两个插入操作将是事务性的,所以如果插入到ItemDetails失败,插入到产品将不会被提交。

根据我在这里找到的信息:http://msdn.microsoft.com/en-us/library/bb738523.aspx
谁能告诉我解决这个问题的最佳方法是什么,我会以错误的方式解决这个问题吗?

提前谢谢。
这是我想要使用的代码示例:


Hi there,

Im working on a website where im using EF.

I have two tables: Products and ItemDetails. Products is simple, it contains the id and name of the product. ItemDetails contains some additional information which
is applicable to more than one type of item, meaning other than Products.
When i create a product in the Products table i also create an associated record in the ItemDetails. Because ItemDetails can contain details associated with records from other tables
im not using a foreign key relationship between the Products and ItemDetails tables.

My requirement is that the two insert operations will be transactional so if the insert to ItemDetails fails the insert to Products will not be committed.

Based on information i found here: http://msdn.microsoft.com/en-us/library/bb738523.aspx
i got this working but i have a big concern, as far as i understand the Transaction will put a lock on the Products table which means that no operation can read or write to that table,
since this is a website there can definitely be more users who wish to operate on this table at the same time the lock is in place.

Can anyone tell me what will be the best approach to solve this, am i going about it in the wrong way?

Thanks in advance.

This is an example of the code i want to use:


var ctx = new
 MyDBEntities();
try { using (var transaction = new TransactionScope())
  {
 try  {
var user = ctx.UserEntities.First();
 var product = new Product(user);
 product.Created = DateTime.Now;
 product.Title = "test" ;
product.Description = "bla bla bla" ; ctx.AddToProductEntities(product); ctx.SaveChanges();
var det = new ItemDetails(product.ID); det.Visibility = 1; ctx.AddToItemDetails(det); ctx.SaveChanges();
transaction.Complete();
Console.WriteLine("Commiting Transaction!" );
 } catch (Exception ex) { Console.WriteLine("exception:" + ex.Message); Console.WriteLine(ex.StackTrace); } } } finally { ctx.Dispose(); Console.WriteLine("context disposed!" ); }

推荐答案

嗨*,

你可以将两个对象添加到上下文然后调用SaveChanges。 SaveChanges默认处于事务中,因此您不必担心创建一些孤立的记录。
Hi *,

you can add both objects into context and then call SaveChanges. SaveChanges is in transaction by default, hence you don't have worry about creating some orphaned records.


这篇关于TransactionScope中的多个插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆