Logging every data change with Entity Framework

后端 未结 8 1045
醉酒成梦
醉酒成梦 2020-12-02 14:43

There is a need from a customer to log every data change to a logging table with the actual user who made the modification. The application is using one SQL user to access t

8条回答
  •  佛祖请我去吃肉
    2020-12-02 15:21

    Simply force an execution of the SET CONTEXT_INFO by using your DbContext or ObjectContext:

    ...
    FileMoverContext context = new FileMoverContext();
    context.SetSessionContextInfo(Environment.UserName);
    ...
    context.SaveChanges();
    

    FileMoverContext inherits from DbContext and has a SetSessionContextInfo method. Here is what my SetSessionContextInfo(...) looks like:

    public bool SetSessionContextInfo(string infoValue)
    {
       try
       {
          if (infoValue == null)
             throw new ArgumentNullException("infoValue");
    
          string rawQuery =
                       @"DECLARE @temp varbinary(128)
                         SET @temp = CONVERT(varbinary(128), '";
    
          rawQuery = rawQuery + infoValue + @"');
                        SET CONTEXT_INFO @temp";
          this.Database.ExecuteSqlCommand(rawQuery);
    
          return true;
       }
       catch (Exception e)
       {
          return false;
       }
    }
    

    Now you just set up a database trigger which can access the CONTEXT_INFO() and set a database field using it.

提交回复
热议问题