I don't want mongodb to create a date/time field, if i am passing a null value, the code below works for all non-date types but fails for the date type. It creates a date/time field with a null value instead. This is a code snippet of my bsondocument below
{"stringfield", stringfield= string.IsNullOrWhiteSpace(stri ngfield)?null:stringfield},
{"datetime", datetime.HasValue == false ?null:datetime}
Note: I am not making use of any classes to map mongodb fields to properties, rather directly creating a bsondocument and inserting that document in mongodb.
I tried using the Convention pack with the following code below, but i guess that applies only when i create classes to map mongofields to properties?
var pack = new ConventionPack();
var ignoreIfNull = new IgnoreIfNullConvention(true);
pack.Add(ignoreIfNull);
ConventionRegistry.Register(" ignoreNulls", pack, t => true);
Conventions only apply when you are mapping classes and not to BsonDocuments.
The best way, in this case, is to simply not add "datetime" to the document when it's null. There is an overload of the Add method you can use which would look like this...
{ "datetime", () => datetime.Value, datetime.HasValue }
You can use Bson Attributte:
[BsonIgnoreIfDefault]
[BsonElement("de")]
[BsonElement("de")]
public DateTime? Created {get;set;}
Best Regards,
Nguyen Quang Huy
@Craig : Thanks a million !! I was unaware of an overloaded version that you displayed below, how come the VS intellisense does not show it?
Thank You once again for letting me know of this, it works perfectly and it surely helped me reduce an unnecessary if-else block of code!
@Nguyen : Thanks for your help, much appreciated!!, but your solution is only applicable if i create entity classes that map to bsonDocuments, in my case i am straightaway creating and inserting a bsonDocument in which case @Craig's solution works perfectly!
댓글 없음:
댓글 쓰기