使用 NHibernate 设置最后修改者和修改者的最佳实践是什么?
在我的应用程序中,我遇到一种情况,我们需要捕获创建和修改记录的时间以及执行这些操作的用户。所以我可能有一个类似这样的对象:
public class Product
{
int Id;
int Name;
DateTime CreatedOn;
int CreatedByUserId;
DateTime LastModifiedOn;
int LastModifiedByUserId;
}
在 NHibernate 中处理这些问题的最佳实践是什么?通过使用拦截器,类似于 这里?
In my application I have a situation where we need to capture the when a record was created and modified and what user performed those actions. So I might have an object something like:
public class Product
{
int Id;
int Name;
DateTime CreatedOn;
int CreatedByUserId;
DateTime LastModifiedOn;
int LastModifiedByUserId;
}
What's the best practice for handling these in NHibernate? Via using an interceptor something like what's described here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为没有“最佳”实践,但使用事件侦听器对此更为常见。 http://ayende 有一个很好的例子.com/Blog/archive/2009/04/29/nhibernate-ipreupdateeventlistener-amp-ipreinserteventlistener.aspx
您需要考虑的一件事是您需要将该 userId 存储在某处。我目前正在通过在启动时在侦听器上分配静态属性来实现此目的。它并不漂亮,但它可以完成工作。
I don't think there's a "best" practice, but the use of event listeners is more common for this. There's a good example at http://ayende.com/Blog/archive/2009/04/29/nhibernate-ipreupdateeventlistener-amp-ipreinserteventlistener.aspx
One thing you'll need to consider is that you need to store that userId somewhere. I'm currently doing that by assigning a static property on the listener on startup. It's not pretty, but it gets the job done.
我同意迭戈的观点,我认为没有最佳实践。这取决于您的应用程序上下文。在Diego的链接中,要在持久性(nHibernate)级别使用事件侦听器,它需要知道如何查找当前用户。根据您的应用程序,这可能没有意义。例如,如果您正在编写 ASP.NET MVC 应用程序,您真的希望持久层依赖 HttpContext 来了解用户吗?是的,您可以传递某种类型的策略,但这似乎并不总是正确的做法。
我认为让服务层构建对象并添加创建者本身是完全有效的。然后将整个对象(创建者已经水合)传递给 nHibernate 进行持久化。创建者将以与任何其他属性相同的方式保存到数据库中。
I agree with Diego that I don't think there's a best practice. It depends on your application context. In Diego's link, and to use event listeners at the persistence (nHibernate) level, it needs to know how to lookup the current user. This may not make sense depending on your application. For example, if you're writing an ASP.NET MVC app, do you really want your persistence layer to depend on HttpContext to know the user? Yes, you could pass in some type of strategy, but this doesn't seem like it's always going to be the right thing to do.
I think it's perfectly valid to have your service layer construct the object and add the creator itself. Then pass the whole object, with the creator already hydrated, down to nHibernate to persist. The creator would be saved to the database the same way as any other property.