From b3868f21fd2b8e4c02314e5043becb3948066536 Mon Sep 17 00:00:00 2001 From: JKamsker Date: Tue, 20 Feb 2024 22:19:07 +0100 Subject: [PATCH] Fix issue: Id is null when anon. type is de/-serialized --- LiteDB.Tests/Document/Bson_Tests.cs | 25 ++++++++++++++++++- .../Client/Mapper/BsonMapper.Deserialize.cs | 8 +++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/LiteDB.Tests/Document/Bson_Tests.cs b/LiteDB.Tests/Document/Bson_Tests.cs index fa8085dd7..c8b464caa 100644 --- a/LiteDB.Tests/Document/Bson_Tests.cs +++ b/LiteDB.Tests/Document/Bson_Tests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using FluentAssertions; using Xunit; @@ -115,5 +115,28 @@ public void Bson_Partial_Deserialize() doc4.ToString().Should().Be(src.ToString()); } + + [Fact] + public void BsonMapper_AnonymousType() + { + var mapper = new BsonMapper(); + + var obj = new + { + Id = 1, + Name = "John" + }; + + var doc = mapper.ToDocument(obj); + var obj2 = DeserializeAnonymous(mapper, doc, obj); + + Assert.Equal(obj.Id, obj2.Id); + Assert.Equal(obj.Name, obj2.Name); + + static T DeserializeAnonymous(BsonMapper mapper, BsonDocument doc, T obj) + { + return mapper.Deserialize(doc); + } + } } } \ No newline at end of file diff --git a/LiteDB/Client/Mapper/BsonMapper.Deserialize.cs b/LiteDB/Client/Mapper/BsonMapper.Deserialize.cs index 0f3e6259e..3b24d4b2c 100644 --- a/LiteDB/Client/Mapper/BsonMapper.Deserialize.cs +++ b/LiteDB/Client/Mapper/BsonMapper.Deserialize.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Collections; using System.Collections.Generic; @@ -309,6 +309,12 @@ private object DeserializeAnonymousType(Type type, BsonDocument value) { var arg = this.Deserialize(par.ParameterType, value[par.Name]); + // if name is Id and arg is null, look for _id + if (arg == null && StringComparer.OrdinalIgnoreCase.Equals(par.Name, "Id") && value.TryGetValue("_id", out var id)) + { + arg = this.Deserialize(par.ParameterType, id); + } + args.Add(arg); }