[英]Rollingback a transaction in .Net Entity Framework
I have an MVC Action Controller method as: 我有一个MVC动作控制器方法,如下所示:
public ActionResult Register(ViewModel.User model)
{
DbContextTransaction dbTransaction = null;
if (ModelState.IsValid)
{
try
{
UserAccountLogic registerUser = new UserAccountLogic();
dbTransaction = registerUser.RegisterUser(model);
Mail.SendEmail(model.Email, model.FirstName);
dbTransaction.Commit();
//Session["Email"] = model.Email;
ViewBag.Style = "block";
}
catch (Exception e)
{
dbTransaction.Rollback();
log.Error(e.Message, e);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
RegisteredUser function is in Business Layer as: RegisteredUser函数在业务层中的位置为:
public DbContextTransaction RegisterUser(User model)
{
//var userEntity = Mapper.Map<User, Dal.UserInfo>(model);
var userEntity = MapModelToEntity(model);
var registerService = new Dal.AccountService();
return registerService.SaveRegisterDetails(userEntity);
}
and SaveRegisterDetails function is in DataAccessLayer as: 和SaveRegisterDetails函数在DataAccessLayer中的形式为:
public DbContextTransaction SaveRegisterDetails(UserInfo registerDetails)
{
//TransactionModel transactionModel = new TransactionModel();
using (HealthCarePortalEntities context = new HealthCarePortalEntities())
{
using (DbContextTransaction dbTran = context.Database.BeginTransaction())
{
context.UserInfo.Add(registerDetails);
context.SaveChanges();
return dbTran;
}
}
Now my problem is I want to rollback a transaction ie a newly registered user data from the database when there is any exception in sending activation link to the user. 现在我的问题是,当向用户发送激活链接时出现异常时,我想回滚事务,即从数据库中新注册的用户数据。 But the problem is the part where I am doing rollback an exception throws because the Database connection is null.
但是问题是我正在回滚的部分发生异常,因为数据库连接为空。 So my question is how can I get the connection of DAL layer in Controller which is in another layer.
所以我的问题是我如何才能在另一层的Controller中获得DAL层的连接。 Thanks for the help.
谢谢您的帮助。
You only need to implement IDisposable
您只需要实现
IDisposable
private void Dispose(bool disposing)
{
// ...
if (disposing && (this._innerConnection != null))
{
this._disposing = true;
this.Rollback(); // there you go
}
}
You could use the ambient transaction model. 您可以使用环境交易模型。
using(TransactionScope tran = new TransactionScope()) {
UserAccountLogic registerUser = new UserAccountLogic();
dbTransaction = registerUser.RegisterUser(model);
Mail.SendEmail(model.Email, model.FirstName);
tran.Complete();
}
That way if an exception occurs inside your transaction scope the db rolls back the data. 这样,如果事务范围内发生异常,则数据库将回滚数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.