asp.net MVC created_by,modified_by,created_time,modified_time自动处理

时间:2018-07-15 05:54:30

标签: c# entity-framework code-first

我是ASP.net MVC的新手,从代码优先模型开始
在几乎所有的数据库表中,我都有4个相同的字段

  1. created_by:不为null(仅创建时的用户ID)
  2. modified_by:允许为空(每次编辑都会保存由用户ID修改的最后一个内容)
  3. created_time:不为null(当前日期时间)
  4. modified_time:允许为空(每次编辑都将保存上次修改的日期时间)

我希望某个函数一次对所有表进行全局管理,但要进行这样的检查

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_())

请帮助我使用此功能以及在哪里放置它。因为在每个模型构造中编写相同的功能看起来并不好。

1 个答案:

答案 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
    }
}