我目前正在使用 ASP.NET Web Api 以及 NHibernate 和 Autofac...我遇到了一个问题,我的更新没有提交到数据库。每次执行操作时,我都使用 ActionFilterAttribute 打开和关闭事务,如下所示:
private ISessionFactory SessionFactory { get; set; }
public TransactionAttribute()
{
SessionFactory = WebApiApplication.SessionFactory;
}
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var session = SessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
session.BeginTransaction();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var session = SessionFactory.GetCurrentSession();
var transcation = session.Transaction;
if (transcation != null && transcation.IsActive)
{
transcation.Commit();
}
session = CurrentSessionContext.Unbind(SessionFactory);
session.Close();
}
这对我的存储库中的添加、读取和删除功能来说效果很好。不幸的是,我的更新似乎不起作用(虽然我已经尝试了几种方法):
public bool Update(Client client)
{
var result = Get(client.ClientID);
if (result == null)
{
return false;
}
result.Name = client.Name;
result.Acronym = client.Acronym;
result.Website = client.Website;
return true;
}
根据我的阅读,如果在事务期间修改对象,则无需手动调用 Update 或 SaveOrUpdate,因为这是由 NHibernate 跟踪并在提交事务时执行的。
为什么我的更新功能无法正常工作?
谢谢!
最佳答案
这是我自己想出来的——基本上我创建了 2 个 session (一个在我的 TranscationAttribute 中,另一个由于 DI 到我的存储库中)。它创建两个的原因在 OnActionExecuting 语句中非常明确......我没有检查当前是否有任何 session 工厂绑定(bind)到 CurrentSessionContext。这是我正在使用的新代码:
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (!CurrentSessionContext.HasBind(SessionFactory))
{
CurrentSessionContext.Bind(SessionFactory.OpenSession());
}
var session = SessionFactory.GetCurrentSession();
session.BeginTransaction();
}
我在实现这段代码后遇到的问题是逻辑不合理。当 session 被 DI 到我的存储库 ISession 中时,它没有被自动绑定(bind)。我的解决方案是像这样将它绑定(bind)到我的存储库的构造函数中:
public ClientRepository(ISession session)
{
if (session == null) throw new ArgumentNullException("nhSession");
this._session = session;
CurrentSessionContext.Bind(_session);
}
但我不能 100% 确定这对于许多并发 HTTP 请求来说是安全的...除非有人在这里为我提供答案,否则我将把这个问题提交给代码审查!
谢谢!
关于c# - 为什么我的 NHibernate 更新不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13003455/