Skip to content

Commit

Permalink
Merge pull request #2433 from JKamsker/anonymous_type_deserialization…
Browse files Browse the repository at this point in the history
…_fix

Fix issue: Id is null when anon. type is de/-serialized
  • Loading branch information
mbdavid authored Feb 21, 2024
2 parents 6db7450 + b3868f2 commit f856062
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
25 changes: 24 additions & 1 deletion LiteDB.Tests/Document/Bson_Tests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using FluentAssertions;
using Xunit;
Expand Down Expand Up @@ -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<T>(BsonMapper mapper, BsonDocument doc, T obj)
{
return mapper.Deserialize<T>(doc);
}
}
}
}
8 changes: 7 additions & 1 deletion LiteDB/Client/Mapper/BsonMapper.Deserialize.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
Expand Down Expand Up @@ -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);
}

Expand Down

0 comments on commit f856062

Please sign in to comment.