we are having DateTime field and we are reading from MongoDB collection and deserialising into that class. Lets say if it has null in DateTime DB field and MongoDriver is trying to set null to that datetime field which is non nullable type . It s throwing error.
.FindAll().ToList() => error in here.
Any help to overcome this problem ?
Note that : We can use nullable Datetime (DateTime?) . but we need Non nullable type only in domain model. So i just want to use non nullable DateTime while serializing
There are two possibilities for
nullin this case. You could have stored an actualnullin your database:Or you are not storing the field at all:
In the first case, you could handle this by creating your own serializer:
(In this case, giving the current date whenever a
nullis serialized or de-serialized)You would then need to register this as the serializer for the DateTime type:
It has to be said that it would be easier to sanitize the data at the source, so that it didn’t have
nullsin the first place.In the second case, this has been handled by the C# driver for MongoDB since 1.5, which version are you using? You could set the default value by registering your own class map, like the following, but as mentioned above it should no longer be required.