Skip to content

Commit

Permalink
Allow deserializling MongoDb collection entries
Browse files Browse the repository at this point in the history
which are missing entries for nullalbe fields.
  • Loading branch information
TimHolzherr committed Nov 2, 2020
1 parent 878ba12 commit 7f89c87
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
20 changes: 19 additions & 1 deletion src/Context.Tests/ImmutableConventionTests.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using Snapshooter.Xunit;
using Squadron;
using Xunit;

namespace MongoDB.Extensions.Context.Tests
{
public class ImmutableConventionTests
public class ImmutableConventionTests
{
public class SimpleImmutableCase : IClassFixture<MongoResource>
{
Expand Down Expand Up @@ -104,6 +105,23 @@ public async Task ApplyConvention_WithoutValue_SerializeSuccessful()
result.MatchSnapshot();
}

[Fact]
public async Task ApplyConvention_WithoutValueInDb_SerializeSuccessful()
{
// Arrange
IMongoCollection<A> collectionTyped =
_context.Database.GetCollection<A>("test");
IMongoCollection<BsonDocument> collectionUntyped =
_context.Database.GetCollection<BsonDocument>("test");

// Act
await collectionUntyped.InsertOneAsync(new BsonDocument {{"_A", "a"}});

// Assert
A result = await collectionTyped.FindSync(FilterDefinition<A>.Empty).FirstAsync();
result.MatchSnapshot();
}

[Fact]
public async Task ApplyConvention_WithValue_SerializeSuccessful()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"_A": "a",
"_B": null
}
14 changes: 13 additions & 1 deletion src/Context/ImmutableConvention.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ internal class ImmutableConvention
, IClassMapConvention
{
private readonly BindingFlags _bindingFlags;
private readonly string _nullableAttributeFullName =
"System.Runtime.CompilerServices.NullableAttribute";

public ImmutableConvention()
: this(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
Expand All @@ -35,7 +37,11 @@ public void Apply(BsonClassMap classMap)

foreach (PropertyInfo property in mappingProperties)
{
classMap.MapMember(property);
BsonMemberMap member = classMap.MapMember(property);
if (IsNullableProperty(property))
{
member.SetDefaultValue((object)null);
}
}

if (!classMap.ClassType.IsAbstract)
Expand All @@ -57,6 +63,12 @@ public void Apply(BsonClassMap classMap)
}
}

private bool IsNullableProperty(PropertyInfo propertyInfo)
{
return propertyInfo.CustomAttributes
.Any(a => a.AttributeType.FullName == _nullableAttributeFullName);
}

private static List<PropertyInfo> GetMatchingProperties(
ConstructorInfo constructor,
List<PropertyInfo> properties)
Expand Down

0 comments on commit 7f89c87

Please sign in to comment.