0

我第一次与NHibernate一起开发ASP.NET MVC和StructureMap。 CodeCampServer是一个很好的例子。我非常喜欢那里实施的不同概念,我可以从中学到很多东西。当存储库被构造函数传递时,NHibernate不更新实体

在我的控制器中,我使用Constructur依赖注入来获取所需特定存储库的实例。

我的问题是:如果我改变客户对客户的数据是不是在数据库中更新的属性,虽然提交()被调用的交易对象(通过HTTP模块)。

public class AccountsController : Controller 
{ 
    private readonly ICustomerRepository repository; 

    public AccountsController(ICustomerRepository repository) 
    { 
     this.repository = repository; 
    } 

    public ActionResult Save(Customer customer) 
    { 
     Customer customerToUpdate = repository 
      .GetById(customer.Id); 

     customerToUpdate.GivenName = "test"; //<-- customer does not get updated in database 
     return View();  
    } 
} 

在另一方面,这是工作:

public class AccountsController : Controller 
{ 
    [LoadCurrentCustomer] 
    public ActionResult Save(Customer customer) 
    { 
     customer.GivenName = "test"; //<-- Customer gets updated 
     return View();    
    } 
} 

public class LoadCurrentCustomer : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     const string parameterName = "Customer"; 

     if (filterContext.ActionParameters.ContainsKey(parameterName)) 
     { 
      if (filterContext.HttpContext.User.Identity.IsAuthenticated) 
      {      
       Customer CurrentCustomer = DependencyResolverFactory 
        .GetDefault() 
        .Resolve<IUserSession>() 
        .GetCurrentUser(); 

       filterContext.ActionParameters[parameterName] = CurrentCustomer; 
      } 
     } 

     base.OnActionExecuting(filterContext); 
    } 
} 

public class UserSession : IUserSession 
{ 
    private readonly ICustomerRepository repository; 

    public UserSession(ICustomerRepository customerRepository) 
    { 
     repository = customerRepository; 
    } 

    public Customer GetCurrentUser() 
    { 
     var identity = HttpContext.Current.User.Identity; 

     if (!identity.IsAuthenticated) 
     { 
      return null; 
     } 

     Customer customer = repository.GetByEmailAddress(identity.Name); 
     return customer; 
    } 
} 

我也试图致电类似下面的代码显示了库更新。但是这会导致一个NHibernateException,它说“非法尝试将一个集合与两个打开的会话关联”。其实只有一个。

public ActionResult Save(Customer customer) 
{ 
    Customer customerToUpdate = repository 
     .GetById(customer.Id); 

    customer.GivenName = "test"; 
    repository.Update(customerToUpdate); 

    return View(); 
} 

有人知道为什么客户没有在第一个例子中更新,但在第二个例子中更新吗?为什么NHibernate会说有两个打开的会话?

回答

0

尝试调用repository.Flush()

0

最后我发现了这个问题。当我通过ID获取客户时,我总是打开一个新的会话,而不是在请求范围内使用会话。

但是,非常感谢您的帮助!

相关问题