如何使用 Castle ActiveRecord 在保存或更新过程中自动填充字段
问题: 我们数据库中的所有表都有 CreatedDate、CreatedBy、ChangedDate、ChangedBy 字段,我希望在保存/更新 ActiveRecord 实体时自动设置这些字段。
我的第一次尝试是重写 Save() 和 Update() 方法。 但只有当我对实体执行直接 Save() 或 Update() 操作时,才会调用这些方法。 它们不会在主 - 详细信息场景中被调用,在该场景中我仅在主上调用 Save() 。
接下来尝试的是 OnSave() 和 OnUpdate() 方法,但此处字段中的更改未保留在数据库中。
最后我尝试了BeforeSave()方法。 但更新时不会调用该方法。
问题: 如何在 Save() 或 Update() 期间自动设置这些 CreatedDate、CreatedBy、ChangedDate、ChangedBy 字段?
The Problem:
All tables in our database have CreatedDate, CreatedBy, ChangedDate, ChangedBy fields which I want to be set automatically when Saving / Updating an ActiveRecord entity.
My first try was to override the Save() and Update() methods. But these methods only get called when I do a direct Save() or Update() on the entity. They are not being called in a Master - Detail scenario where I call Save() only on the master.
Next try were the OnSave() and OnUpdate() methods, but here changes in the fields were not persisted in the database.
Finally I tried the BeforeSave() method. But this method is not called when updating.
The Question:
How can set these CreatedDate, CreatedBy, ChangedDate, ChangedBy fields automatically during a Save() or Update()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以这样做
you could do like this
我遇到了同样的问题并以这种方式解决了它:
我使用
OnUpdate()
和OnSave()
。 正如您所提到的,此解决方案不适用于主详细信息场景。 为此,我明确设置了每个孩子的父母。 注意以下代码:I had a same problem and solved it this way:
I use
OnUpdate()
andOnSave()
. As you mentioned this solution does not work with master detail scenarios. For this I set parent of each child explicitly. Note following codes:要根据需要修改数据,您必须重写 BeforeSave 方法,如下所示:
最后保存实例:
我通常使用 SaveCopy() 来利用重写方法 FindDirty(object id, IDictionary previousState, IDictionary currentState, NHibernate.Type .IType[] 类型)来获取该类的先前值。
希望能帮助到你。
To modify data as you you want you have to override the BeforeSave method like this:
And finally save your instance:
I usually use SaveCopy() to make use of the overriden method FindDirty(object id, IDictionary previousState, IDictionary currentState, NHibernate.Type.IType[] types) to get the previous values of the class.
Hope it helps.
使用 BeforeSave() 进行保存,使用 OnFlushDirty() 进行更新。
Use BeforeSave() for saving and OnFlushDirty() for updating.