我是ASP.net MVC的新手,从代码优先模型开始
在几乎所有的数据库表中,我都有4个相同的字段
我希望某个函数一次对所有表进行全局管理,但要进行这样的检查
from PyQt5 import QtCore, QtWidgets
class FileSystemView(QtWidgets.QTreeView):
def __init__(self, parent=None):
super(FileSystemView, self).__init__(parent)
self.model = QtWidgets.QFileSystemModel()
self.model.setRootPath(QtCore.QDir.homePath())
self.setModel(self.model)
self.setRootIndex(self.model.index(QtCore.QDir.homePath()))
self.model.setReadOnly(False)
self.setAnimated(False)
self.setSortingEnabled(True)
self.setEditTriggers(QtWidgets.QTreeView.NoEditTriggers)
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showContextMenu)
def showContextMenu(self, point):
ix = self.indexAt(point)
if ix.column() == 0:
menu = QtWidgets.QMenu()
menu.addAction("Rename")
action = menu.exec_(self.mapToGlobal(point))
if action:
if action.text() == "Rename":
self.edit(ix)
if __name__ == '__main__':
import sys
app =QtWidgets.QApplication(sys.argv)
w = FileSystemView()
w.show()
sys.exit(app.exec_())
请帮助我使用此功能以及在哪里放置它。因为在每个模型构造中编写相同的功能看起来并不好。
答案 0 :(得分:1)
已经有一段时间了,但是在您的DbContext
中,您可以在SaveChangesAsync
上放置替代。我将修复一些伪代码功能的示例。
更新,我将尝试修复更具体的示例
//you can put this anywhere you want
public interface IAuditableEntity
{
//helper interface. put it on the entities you want to trace.
string created_by {get;set;}
DateTime created_time {get;set;}
//todo: add more properties like 'modified'
}
将此接口放在您要跟踪的实体上:
//Here you reuse the interface
public class YourTableEntity : IAuditableEntity
{
//implement members...
}
然后在您的数据上下文中:
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
WriteAutoData();
return base.SaveChangesAsync(cancellationToken);
}
//just a helper function
private void WriteAutoData()
{
foreach (var entry in ChangeTracker.Entries().OfType<IAuditableEntity>().Where(c =>
c.State != EntityState.Detached &&
c.State != EntityState.Unchanged))
{
//the `entry` is of type IAuditableEntity, so you can access it's members
if (entry.State == EntityState.Added)
{
entry.created_by = "your user";
entry.created_time = DateTime.UtcNow;
}
else if (entry.State == EntityState.Modified)
{
//modified data here
}
else if (entry.State == EntityState.Deleted)
//deleted logic here: you are not using this. You could use it to log a delete
}
}