Sib*_*ain 2 .net c# mysql json dapper
我在MySQL数据库中有一个表,其中包含一个JSON数据类型列.是否可以检索存储在该列中的JSON数据并使用Dapper映射到我的c#类?下面是关于数据如何存储在列中的示例JSON.
[
{
"ServerName": "",
"Priority": 1,
"FilesystemBasePath": "",
"IsAvailable": 1,
"ApplicationDocumentType": ""
},
{
"ServerName": "",
"Priority": 2,
"FilesystemBasePath": "",
"IsAvailable": 1,
"ApplicationDocumentType": ""
}
]
Run Code Online (Sandbox Code Playgroud)
我希望数据映射到List<MyObject>C#中的类型.
您注册了ITypeHandler List<MyObject>,或者注册属性类型.
public class MyClass
{
public List<MyObject> MyObjects {get; set;
}
public class JsonTypeHandler: SqlMapper.ITypeHandler
{
public void SetValue(IDbDataParameter parameter, object value)
{
parameter.Value = JsonConvert.SerializeObject(value);
}
public object Parse(Type destinationType, object value)
{
return JsonConvert.DeserializeObject(value as string, destinationType);
}
}
SqlMapper.AddTypeHandler(typeof(List<MyObject>),new JsonTypeHandler());
Run Code Online (Sandbox Code Playgroud)
之后,如果您有一个映射到类型属性的列名,List<MyObject>它将被正确序列化和反序列化.