“Conversion of a datetime2 data type to a datetime” error in Entity Framework

I was following the very helpful tutorial at http://msdn.microsoft.com/en-us/data/jj206878, taking my first crack at Entity Framework. Yes, I’m more than a little behind the curve on that technology. But, no time like the present to catch up.

To be honest, I was “mostly following” the tutorial. I went off and created my own User table, the script of which is:

CREATE TABLE [dbo].[User] (     
[Id]          INT           IDENTITY (1, 1) NOT NULL,
[FirstName]   VARCHAR (50)  NOT NULL,
[LastName]    VARCHAR (50)  NOT NULL,
[Email]       VARCHAR (100) NOT NULL,
[Password]    VARCHAR (50)  NOT NULL,
 [CreatedDate] DATETIME      DEFAULT (getdate()) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

And I continued to mostly follow along with the tutorial, generating the various EF classes, and wrote code to insert values into the database using the wonderful EF stuff:

protected void Button1_Click(object sender, EventArgs e)         
{
             using (var db = new Entries())
             {
                 var newUser = new User { FirstName = txt1.Text, LastName = txt2.Text, Email = txt3.Text, Password = txt4.Text };
                 db.Users.Add(newUser);
                 db.SaveChanges();
                var queryUsers = from u in db.Users
                                  orderby u.LastName
                                  select u;
                foreach (var item in queryUsers)
                 {
                     Response.Write("<br>User = " + item.FirstName + " " + item.LastName);
                 }
             }
 }

 

When I ran my incredibly complex code, I received this unhappy message courtesy of a System.Data.Entity.Infrastructure.DbUpdateException:

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

This was because I had marked my CreatedDate field as nullable. I had thought that the database would just do its thing and create the date when the record was inserted, but EF didn’t like that. So what I did was populate the date in C# code, and that worked out:

var newUser = new User{FirstName = txt1.Text, LastName = txt2.Text, Email = txt3.Text, Password = txt4.Text
, CreatedDate = DateTime.Now};
Advertisements

,

  1. #1 by pedro on September 2, 2014 - 9:30 am

    Hi, this is just to let you know that your post has solved my problem.
    Thank you very much.

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: