DateTime out-of-range error in Entity Framework

Trying to add a new object to my context in MVC / Entity Framework, I ran into this error:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.

I was, in fact, just adding a minimum date to my property, so I didn’t see the problem:

using (UsersContext db = new UsersContext()) {
  db.UserProfiles.Add(new UserProfile { UserName = model.UserName, 
    DateLastLoggedIn = DateTime.MinValue });
  db.SaveChanges();
}

Through the miracle of Stack Overflow, I discovered that I needed to set a DateTime greater than the minimum date. So I picked an arbitrary date

db.UserProfiles.Add(new UserProfile { UserName = model.UserName, 
DateLastLoggedIn = new DateTime(1982, 1, 1) });

I chose 1982 because that is when “I Ran” by “Flock of Seagulls” was released. But choose the release date for your favorite song,  even if, for some reason, it’s by Miley Cyrus, and you should be OK.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: