Skip to content

Commit ad0ad17

Browse files
authored
CSHARP-3703: Fix NullReferenceException when Id property has no getter. (#545)
1 parent 61fa138 commit ad0ad17

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/MongoDB.Bson/Serialization/Conventions/NamedIdMemberConvention.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,9 @@ private bool IsValidIdMember(BsonClassMap classMap, MemberInfo member)
112112
if (member is PropertyInfo)
113113
{
114114
var getMethodInfo = ((PropertyInfo)member).GetMethod;
115-
if (getMethodInfo.IsVirtual && getMethodInfo.GetBaseDefinition().DeclaringType != classMap.ClassType)
115+
if (getMethodInfo == null ||
116+
getMethodInfo.IsVirtual &&
117+
getMethodInfo.GetBaseDefinition().DeclaringType != classMap.ClassType)
116118
{
117119
return false;
118120
}

tests/MongoDB.Bson.Tests/Serialization/Conventions/IdMemberConventionsTests.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ private class TestClassD
4444
public ObjectId _id { get; set; }
4545
}
4646

47+
private class TestClassNoIdGetter
48+
{
49+
public Object Id
50+
{
51+
set { }
52+
}
53+
}
54+
4755
[Fact]
4856
public void TestNamedIdMemberConventionWithTestClassA()
4957
{
@@ -82,5 +90,14 @@ public void TestNamedIdMemberConventionWithTestClassD()
8290
Assert.NotNull(classMap.IdMemberMap);
8391
Assert.Equal("_id", classMap.IdMemberMap.MemberName);
8492
}
93+
94+
[Fact]
95+
public void TestNamedIdMemberConventionWillNotReturnIdWithoutGetter()
96+
{
97+
var convention = new NamedIdMemberConvention("Id", "id", "_id");
98+
var classMap = new BsonClassMap<TestClassNoIdGetter>();
99+
convention.Apply(classMap);
100+
Assert.Null(classMap.IdMemberMap);
101+
}
85102
}
86103
}

0 commit comments

Comments
 (0)