我正在尝试使用DbCommand
将实体框架Newtonsoft.Json
序列化为json:
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"]
如何告诉序列化程序序列化整个对象?
答案 0 :(得分:1)
您可以使用自定义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:\Users\miparnisari\Documents\log.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
}
}