我有一个表,我将字典作为json存储在一列中。在向/从数据库保存/加载内容时,我希望能够在可能的情况下使json de / serialization不可见。是否有可能以某种方式使用dapper而不使用包含json表示的Foo中的另一个属性?
// where someData is the dictionary column
void Save(IDbConnection conn, Foo foo){
conn.Execute("INSERT INTO foos (name, <othercols...>, someData) VALUES (@Name, <othercols...>, @SomeData, foo);
}
我可以手动将Foo映射到一个新的动态对象,但是因为有其他列是乏味的,所以我想知道是否还有其他方法?
您可以通过实现ITypeHandler来实现它。
Dictionary<int, string>
示例实现:
class DictTypeHandler : ITypeHandler
{
public object Parse(Type destinationType, object value)
{
return JsonConvert.DeserializeObject<Dictionary<int, string>>(value.ToString());
}
public void SetValue(IDbDataParameter parameter, object value)
{
parameter.Value = (value == null)
? (object)DBNull.Value
: JsonConvert.SerializeObject(value);
parameter.DbType = DbType.String;
}
}
如果使用SqlMapper.AddTypeHandler(typeof(DictTypeHandler), new DictTypeHandler())
将Dapper添加到已知的处理程序中,Dapper将使用该处理程序
如果你的sql-column是varchar(max),请注意将IDbDataParameter.DbType
设置为string,否则Dapper将使用不能转换为varchar(max)的sql_variant。
如果通过存储库模式实现持久性,则可以将AddTypeHandler
代码添加到构造函数中。