(feature): Dictionary<Guid, List<Guid>> serializer

This commit is contained in:
Maksym Sadovnychyy 2025-06-09 22:51:58 +02:00
parent ab2d914c46
commit e5898dbfe7
3 changed files with 33 additions and 3 deletions

View File

@ -16,9 +16,9 @@
</PackageReference> </PackageReference>
<PackageReference Include="MaksIT.Core" Version="1.4.0" /> <PackageReference Include="MaksIT.Core" Version="1.4.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.5" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.5" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" /> <PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.0"> <PackageReference Include="xunit.runner.visualstudio" Version="3.1.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>

View File

@ -8,7 +8,7 @@
<!-- NuGet package metadata --> <!-- NuGet package metadata -->
<PackageId>MaksIT.MongoDB.Linq</PackageId> <PackageId>MaksIT.MongoDB.Linq</PackageId>
<Version>1.1.0</Version> <Version>1.1.1</Version>
<Authors>Maksym Sadovnychyy</Authors> <Authors>Maksym Sadovnychyy</Authors>
<Company>MAKS-IT</Company> <Company>MAKS-IT</Company>
<Product>MaksIT.MongoDB.Linq</Product> <Product>MaksIT.MongoDB.Linq</Product>

View File

@ -0,0 +1,30 @@
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
namespace MaksIT.MaksIT.MongoDB.Linq.Serializers;
public class GuidKeyDictionarySerializer<TValue> : SerializerBase<Dictionary<Guid, TValue>> {
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Dictionary<Guid, TValue> value) {
context.Writer.WriteStartDocument();
foreach (var kvp in value) {
context.Writer.WriteName(kvp.Key.ToString()); // Convert Guid key to string
BsonSerializer.Serialize(context.Writer, kvp.Value);
}
context.Writer.WriteEndDocument();
}
public override Dictionary<Guid, TValue> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) {
var dictionary = new Dictionary<Guid, TValue>();
context.Reader.ReadStartDocument();
while (context.Reader.ReadBsonType() != BsonType.EndOfDocument) {
var key = Guid.Parse(context.Reader.ReadName());
var value = BsonSerializer.Deserialize<TValue>(context.Reader);
dictionary.Add(key, value);
}
context.Reader.ReadEndDocument();
return dictionary;
}
}