如何使用entity-framewrok-4在trasaction中插入数据?
我有一个订单对象,它还有其他需要在事务中插入数据库的集合。
cOrder->
->lstOrderItems
-->lstDressing, lstTopping, lstspecialInstruction
->userDetails
->trasactionTblsdetails
还需要提出意见: - 1)在数据库级别或实体框架级别维护事务是否合适。 2)编码风格应该是什么。
现在我正在以这种方式关注它,但正如我可以预测它需要大量代码但想要知道这只是它的工作方式或更好的解决方案存在。
public static void SaveOrder()
{
using (EposWebOrderEntities Ctx = new EposWebOrderEntities())
{
using (TransactionScope scope = new TransactionScope())
{
// do something...
Ctx.order.SaveChanges();
// do something...
//foreach to save the order items to databaswe
Ctx.orderitems.SaveChanges();
// do something...
//foreach to save in dressing tbl
Ctx.dressing.SaveChanges();
//foreach to save in topping tbl
Ctx.topping.SaveChanges();
//foreach to save in dressing tbl
Ctx.dressing.SaveChanges();
//foreach to save in spinst tbl
Ctx.dressing.SaveChanges();
scope.Complete();
success = true;
}
}
}
答案 0 :(得分:1)
以这种方式使用它。在大多数情况下都足够了。
public static void SaveOrder()
{
using (EposWebOrderEntities Ctx = new EposWebOrderEntities())
{
Ctx.Entry<Order>(order).State = EntityState.Added;
Ctx.Entry<Dressing>(dressing).State = EntityState.Added;
Ctx.SaveChanges();
}
}
http://msdn.microsoft.com/en-us/library/dn456843.aspx
在所有版本的Entity Framework中,每当您执行SaveChanges()以在数据库上插入,更新或删除&gt;时,框架都会将该操作包装在事务中。此事务持续时间仅足以执行操作然后完成。当您执行另一个这样的&gt;操作时,将启动一个新事务。