我可以使用ADO NET实体数据模型创建事务吗?

时间:2010-05-13 22:52:00

标签: c# transactions ado.net-entity-data-model

是否可以在以下try-catch中使用ADO NET实体数据模型将一组语句作为事务执行?

[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Customer c)
{   
    try
    {
        c.Created = DateTime.Now;
        c.Active = true;
        c.FullName = Request.Form["FirstName"];
        db.AddToCustomer(c);
        db.SaveChanges();

        Log log = new Log();//another entity model object
        log.Created = DateTime.Now;
        log.Message = 
            string.Format(@"A new customer was created 
            with customerID {0}", c.CustomerID);
        db.AddToLog(log);

        db.SaveChanges();
        return RedirectToAction("CreateSuccess", "Customer");
    }
    catch
    {
        return View();
    }

}

任何想法都会非常感激。

1 个答案:

答案 0 :(得分:2)

using (var transaction = db.Connection.BeginTransaction())
{
    // your code here
    ...


    transaction.Commit();
}