.Net中Cassandra UDT的map<text,text>转SortedDictionary报错求助
解决Cassandra UDT中Map类型到.NET SortedDictionary的映射异常
问题原因
Cassandra .NET驱动默认会把CQL的map<text,text>类型映射为IDictionary<string, string>,但你的实体属性用的是SortedDictionary<string, string>,驱动没有内置转换器来完成这两种类型的转换,因此抛出类型不兼容的异常。
解决方案
自定义一个类型转换器,实现驱动的ITypeConverter接口,处理IDictionary<string, string>和SortedDictionary<string, string>之间的双向转换,然后在UDT映射中注册这个转换器。
1. 实现自定义转换器
using System; using System.Collections.Generic; using Cassandra.Mapping; public class SortedDictionaryConverter : ITypeConverter { // 从数据库返回的IDictionary转换为SortedDictionary public object ConvertFromDb(object value) { if (value is IDictionary<string, string> dictionary) { return new SortedDictionary<string, string>(dictionary); } return value; } // 把SortedDictionary转换为驱动可处理的IDictionary(写入数据库时用) public object ConvertToDb(object value) { if (value is SortedDictionary<string, string> sortedDict) { return new Dictionary<string, string>(sortedDict); } return value; } public bool CanConvertFrom(Type sourceType) { return typeof(IDictionary<string, string>).IsAssignableFrom(sourceType); } public bool CanConvertTo(Type destinationType) { return typeof(SortedDictionary<string, string>).IsAssignableFrom(destinationType); } }
2. 在UDT映射中注册转换器
假设你的UDT对应的.NET类是YourUdtEntity,修改映射代码如下:
// 全局注册映射和转换器 MappingConfiguration.Global.Define( new Map<YourUdtEntity>() .Map(entity => entity.MyDictionaryTypeProperty, "dictionary_type_property") .WithConverter<SortedDictionaryConverter>(entity => entity.MyDictionaryTypeProperty) );
如果是使用局部的MappingConfiguration实例(而非全局配置):
var mappingConfig = new MappingConfiguration(); mappingConfig.Define( new Map<YourUdtEntity>() .Map(entity => entity.MyDictionaryTypeProperty, "dictionary_type_property") .WithConverter<SortedDictionaryConverter>(entity => entity.MyDictionaryTypeProperty) ); // 使用该配置创建Mapper或会话 var mapper = new Mapper(cassandraSession, mappingConfig);
说明
- 转换器必须实现双向转换:读取数据时把驱动返回的
IDictionary转成SortedDictionary,写入数据时把SortedDictionary转成驱动能识别的普通Dictionary(继承自IDictionary)。 - 替换代码中的
YourUdtEntity为你实际定义的UDT对应.NET类。
内容的提问来源于stack exchange,提问作者Srini V
相关产品推荐
相关产品推荐

