如何在 EF Code First 中创建/更新 LastModified 字段
我想添加一个列,用于在将记录保存到磁盘时存储当前的日期时间。实现这一目标的最佳方法是什么?
我知道这不是一个非常复杂的问题,但我想知道 EF 是否有任何最佳实践或任何功能可以简化任务。 例如:
- 有没有办法将该字段的逻辑包含在表类中,以便在保存到磁盘时自动更新?
- 修改或保存对象时是否需要捕获任何事件?
I want to add a column that stores the current DateTime when a record is saved to disk. What would be the best way to accomplish this?
I know it's not a very complex problem, but I wondered if there is any best practice or any feature of EF that would simplify the task.
For example:
- Is there any way to include the logic for this field inside the table Class, so that it's automatically updated whenever it's saved to disk?
- Is there any event to capture when an object is modified or saved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种选择是创建存储库层并实现您自己的 SaveChanges
one option would be to create repository layer and implement your own SaveChanges
不幸的是,没有您可以订阅的活动。我的建议是重写您的上下文中的 SaveChanges 方法,并在那里执行自定义逻辑(如果您想保持干净,您可以公开您自己的事件)
编辑
我为此选择的一个解决方案是让我的所有实体继承自一个公共对象基类(例如EntityBase)公开方法BeforeSave()和AfterSave(),您可以在重写SaveChanges方法时在自定义DbContext中调用(查看ChangeTracker以获取所有修改的条目)
Unfortunatly there are no events which you can subscribe to. My recommendation is to override the SaveChanges method in your context and do your custom logic there (if you want to keep it clean, you can expose your own events)
EDIT
One solution i picked for this was to let all my entities inherit from a common base class (e.g. EntityBase) which exposes the methods BeforeSave() and AfterSave() which you can call in your custom DbContext when overriding the SaveChanges method ( look at the ChangeTracker for all modified entries )