SQL Server CLR Aggregate: Serialize a Dictionary?

2019-08-29 12:54发布

问题:

I'm writing a custom CLR Aggregate in C# to run in SQL Server 2008. I want to hold most of my SqlUserDefinedAggregate instances' states in Dictionaries, so I can't use the builtin serialization.

How can I go about using UserDefined serialization with the Read() and Write() methods?

回答1:

Using keys and values of types that BinaryReader and BinaryWriter handle, Write each Dictionary out to the BinaryWriter in key0,value0...keyN-1,valueN-1 order. Prefix this sequence with Dictionary's Count. After the sequence, write a constant to verify end of dictionary. Personally I like 0xDEADBEEF.

For deserialization, do the reverse: Intialize a loop to run n times (n is the first integer in your stream), and add to Dictionary as you read in key/value pairs. At the end, check for your constant.