Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8594649
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T00:14:50+00:00 2026-06-12T00:14:50+00:00

we are having DateTime field and we are reading from MongoDB collection and deserialising

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T00:14:51+00:00Added an answer on June 12, 2026 at 12:14 am

    There are two possibilities for null in this case. You could have stored an actual null in your database:

    {
        _id:ObjectId(),
        MyDateTime:null
    }
    

    Or you are not storing the field at all:

    {
        _id:ObjectId()
    }
    

    In the first case, you could handle this by creating your own serializer:

    public class DateTimeSerializer : BsonBaseSerializer
    {
        public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
        {
            var bsonType = bsonReader.CurrentBsonType;
            switch (bsonType)
            {
            case BsonType.Null:
                bsonReader.ReadNull();
                return new DateTime();
            case BsonType.DateTime:
                return bsonReader.ReadDateTime();
            default:
                var message = string.Format("DateTimeSerializer needs a DateTime not {0}.", bsonType);
                throw new BsonSerializationException(message);
            }
        }
    
        public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
        {
            if (value == null)
            {
                TimeSpan nowMs = DateTime.Now-new DateTime(1970,1,1);
                bsonWriter.WriteDateTime((long)nowMs.TotalMilliseconds);
            }
            else
            {
                bsonWriter.WriteString((string)value);
            }
        }
    }
    

    (In this case, giving the current date whenever a null is serialized or de-serialized)

    You would then need to register this as the serializer for the DateTime type:

    BsonClassMap.RegisterClassMap<MyClass>(cm =>
    {
        cm.AutoMap();
        cm.GetMemberMap(mc => mc.MyDateTime).SetSerializer(new DateTimeSerializer());
    });
    

    It has to be said that it would be easier to sanitize the data at the source, so that it didn’t have nulls in 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.

    BsonClassMap.RegisterClassMap<MyClass>(cm =>
    {
       cm.AutoMap();
       cm.GetMemberMap(mc => mc.MyDateTime).SetDefaultValue(new DateTime());
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm having an issue when trying to programmatically update a DateTime field that already
I am rendering out a DateTime field from my view model into two separate
I'm having issues trying to parse a datetime field that I am returning in
We have a very simple payments model with the default created_at datetime field that
I'm having problems when using linq on a datatable.asenumerable(). This throws InvalidCastException. DateTime date=r.Field<DateTime>(date);
I'm having trouble displaying the only date part of a DateTime into a textbox
I am having a problem reading back from windows azure table storage: Here is
I'm having the problem that I cannot get client-side validation to fire from within
My table schema (table Name Stock) Field Date Datetime If Date having datatype is
I'm having a problem saving a datetime object from a form. The form widget

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.