[CSHARP-3703] NullReferenceException when serializing an Id without a getter Created: 03/Jun/21  Updated: 28/Oct/23  Resolved: 04/Jun/21

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: None
Fix Version/s: 2.13.0

Type: Bug Priority: Unknown
Reporter: Nikola Irinchev Assignee: James Kovacs
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: Zip Archive SetterPropertyRepro.zip    
Backwards Compatibility: Fully Compatible

 Description   

If an object has an Id property without a getter, attempting to serialize it to json will throw a NullReferenceException. This is caused by not checking if `GetMethod` is null here: https://github.com/mongodb/mongo-csharp-driver/blob/c8e76e5dd3c11683b5d99f56374754eb1e7ec792/src/MongoDB.Bson/Serialization/Conventions/NamedIdMemberConvention.cs#L114-L118.

I've attached a trivial repro that you can run and test locally.



 Comments   
Comment by James Kovacs [ 04/Jun/21 ]

Thanks for providing the context. That's helpful to know. I was wondering how you got yourself into a situation when your Id didn't have a getter, but Unity stripping unused methods/properties makes a lot of sense.

Comment by Nikola Irinchev [ 04/Jun/21 ]

Thanks James - I agree it's fairly awkward scenario - I hit it when compiling a Unity project where the linker had stripped the getter from my Id property. The NRE threw me off and made me think it had actually stripped something from MongoDB.Bson and it took some digging to get to the bottom of it. Since we'll be shipping Unity support for Realm soon, I figured others might run into it as well.

Comment by James Kovacs [ 04/Jun/21 ]

Hi, nikola.irinchev,

Thank you for reporting this issue. While having an Id without a getter isn't a common design choice, we shouldn't throw a NullReferenceException when attempting to map it. We have implemented a fix, which will be available in an upcoming patch release.

Sincerely,
James

Comment by Githook User [ 04/Jun/21 ]

Author:

{'name': 'James Kovacs', 'email': 'jkovacs@post.harvard.edu', 'username': 'JamesKovacs'}

Message: CSHARP-3703: Fix NullReferenceException when Id property has no getter. (#545)
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/ad0ad177e25debcef9e6f1875f24d4f2c733662a

Generated at Wed Feb 07 21:46:03 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.