Serializing DbCommand with Newtonsoft.Json



我试图用 Newtonsoft.Json序列化实体框架 DbCommand

public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) {
   var path = "C:/result.json";
   File.WriteAllText(path, JsonConvert.SerializeObject(command));
}

但是,在结果JSON文件中,参数是ToString()值,而不是对象:

"Parameters": ["@0", "@1", "@2"]

如何告诉序列化器序列化整个对象?

您可以使用自定义JsonConverter

记录实际值。

首先,示例查询:

using (var context = new SchoolDbContext("dbConnectionString"))
{
     var id = 11;
     var dni = 36170503;
     var sql = @"SELECT name FROM dbo.students WHERE Id = {0} OR Dni = {1}";
     context.Database.ExecuteSqlCommand(sql, id, dni);
} 

然后,添加一个自定义EF拦截器如下:

public class MyDBConfiguration : DbConfiguration
{
    public MyDBConfiguration()
    {
        DbInterception.Add(new EntityFrameworkInterceptor());
    }
}

public class EntityFrameworkInterceptor : IDbCommandInterceptor
{
    public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        var path = @"C:UsersmiparnisariDocumentslog.json";
        var serialized = JsonConvert.SerializeObject(command, new DbCommandSerializer());
        File.WriteAllText(path, serialized);
    }
}

最后,序列化器:

public class DbCommandSerializer : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var dbCommand = value as DbCommand;
        writer.Formatting = Formatting.Indented;
        writer.WriteStartObject();
        writer.WritePropertyName("Query");
        writer.WriteValue(dbCommand.CommandText);
        writer.WritePropertyName("Parameters");
        writer.WriteStartObject();
        foreach (DbParameter param in dbCommand.Parameters)
        {
            writer.WritePropertyName(param.ParameterName);
            writer.WriteValue(param.Value);
        }
        writer.WriteEndObject();
        writer.WriteEndObject();
        writer.Flush();
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
    public override bool CanConvert(Type objectType)
    {
        return typeof(DbCommand).IsAssignableFrom(objectType);
    }
}

此日志:

{
  "Query": "SELECT name FROM dbo.students WHERE Id = @p0 OR Dni = @p1",
  "Parameters": {
    "p0": 11,
    "p1": 36170503
  }
}

相关内容

  • 没有找到相关文章

最新更新