[英]Why isn't my NHibernate update working?
我目前正在将NHibernate和Autofac与ASP.NET Web Api一起使用...我遇到的问题是我的更新未提交到数据库。 每次执行操作时,我都使用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个会话(一个在我的TranscationAttribute中,另一个是由于DI进入我的存储库)。 它创建两个对象的原因在OnActionExecuting语句中非常明确...我没有检查是否当前有任何会话工厂绑定到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();
}
实现此代码后,我遇到的问题是逻辑不健全。当将会话DI放入我的存储库ISession中时,它没有被自动绑定。 我的解决方案是将其绑定到存储库的构造函数中,如下所示:
public ClientRepository(ISession session)
{
if (session == null) throw new ArgumentNullException("nhSession");
this._session = session;
CurrentSessionContext.Bind(_session);
}
但是我不是100%肯定会同时进行许多HTTP请求是安全的...除非有人在这里为我提供答案,否则请将此问题提交代码审查!
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.