Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何按名称返回模型?_C#_Asp.net Core_Entity Framework Core - Fatal编程技术网

C# 如何按名称返回模型?

C# 如何按名称返回模型?,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,我有两个表格(模型)-学生,学生日志。两个表的所有字段名称相同。除此之外,StudentLogs表将具有DateChanged和NameChangedBy字段 因此,当我更新一个students字段(即名称)时,它会将更改和who by写入StudentLog表。我还有其他的表,比如classes、teachers等,所以我需要一个函数来记录每种类型(classesLog、teachersLog等)的所有更改 在我的学生控制器中,我将学生模型作为对象参数传递给LogEntry构造函数中的控制器。

我有两个表格(模型)-学生,学生日志。两个表的所有字段名称相同。除此之外,StudentLogs表将具有DateChanged和NameChangedBy字段

因此,当我更新一个students字段(即名称)时,它会将更改和who by写入StudentLog表。我还有其他的表,比如classes、teachers等,所以我需要一个函数来记录每种类型(classesLog、teachersLog等)的所有更改

在我的学生控制器中,我将学生模型作为对象参数传递给LogEntry构造函数中的控制器。(我可以将模型作为参数传递还是作为对象传递?)

.LogEntry类如下所示

public class LogEntry
{
    private dbContext _context;
    private string logOperation;
    private string modelName;

    public LogEntry(dbContext Context, object Model ,string LogOperation)
    {
        _context = Context;
        logOperation= LogOperation;
        modelName += (Model.ToString().Replace("Project.Models.", "")) + "Logs";            
    }

    public bool HasLog ()
    {
        if (Type.GetType(modelName).exits??)  // <-- Not sure if possible
        {
            return true;
        }

        return false;
    }

}

DbContext.ChangeTracker
可以处理所有这些。您可以通过在DbContext中重写
saveChangesSync()
来自动执行该过程。为每个实体创建一个日志表不是一个好主意。它可以在一个针对所有实体的变更日志表中完成。为什么这不是一个好主意?其他一些表具有不同的列,因此一个表不能使用。列映射表不需要列来记录更改。您可以将更改后的对象存储为JSON字符串,并引用其类型和id。如果您问这是否是最好的方法,我会告诉您不是。我会试试。谢谢。我用了这个教程——这正是我想要的,谢谢@Brad
await _context.SaveChangesAsync();
public class LogEntry
{
    private dbContext _context;
    private string logOperation;
    private string modelName;

    public LogEntry(dbContext Context, object Model ,string LogOperation)
    {
        _context = Context;
        logOperation= LogOperation;
        modelName += (Model.ToString().Replace("Project.Models.", "")) + "Logs";            
    }

    public bool HasLog ()
    {
        if (Type.GetType(modelName).exits??)  // <-- Not sure if possible
        {
            return true;
        }

        return false;
    }

}
public object UpdateLog ()
{              
    return Model; // return the model of the log and update it in the controller or class. not sure whats best
}