Conversion of a datetime2 data type to a datetime data type results out-of-range value

C#Sql ServerEntity FrameworkDatetimeOrm

C# Problem Overview


I've got a datatable with 5 columns, where a row is being filled with data then saved to the database via a transaction.

While saving, an error is returned:

>The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

It implies, as read, that my datatable has a type of DateTime2 and my database a DateTime; that is wrong.

The date column is set to a DateTime like this:

new DataColumn("myDate", Type.GetType("System.DateTime"))

Question

Can this be solved in code or does something have to be changed on a database level?

C# Solutions


Solution 1 - C#

This can happen if you do not assign a value to a DateTime field when the field does not accept NULL values.

That fixed it for me!

Solution 2 - C#

Both the DATETIME and DATETIME2 map to System.DateTime in .NET - you cannot really do a "conversion", since it's really the same .NET type.

See the MSDN doc page: http://msdn.microsoft.com/en-us/library/bb675168.aspx

There are two different values for the "SqlDbType" for these two - can you specify those in your DataColumn definition?

BUT: on SQL Server, the date range supported is quite different.

DATETIME supports 1753/1/1 to "eternity" (9999/12/31), while DATETIME2 supports 0001/1/1 through eternity.

So what you really need to do is check for the year of the date - if it's before 1753, you need to change it to something AFTER 1753 in order for the DATETIME column in SQL Server to handle it.

Marc

Solution 3 - C#

In my SQL Server 2008 database, I had a DateTime column flagged as not nullable, but with a GetDate() function as its default value. When inserting new object using EF4, I got this error because I wasn't passing a DateTime property on my object explicitly. I expected the SQL function to handle the date for me but it did not. My solution was to send the date value from code instead of relying on the database to generate it.

obj.DateProperty = DateTime.now; // C#

Solution 4 - C#

for me it was because the datetime was..

> 01/01/0001 00:00:00

in this case you want to assign null to you EF DateTime Object... using my FirstYearRegistered code as an example

DateTime FirstYearRegistered = Convert.ToDateTime(Collection["FirstYearRegistered"]);
if (FirstYearRegistered != DateTime.MinValue)
{
    vehicleData.DateFirstReg = FirstYearRegistered;
}  

Solution 5 - C#

This one was driving me crazy. I wanted to avoid using a nullable date time (DateTime?). I didn't have the option of using SQL Server 2008's datetime2 type either

modelBuilder.Entity<MyEntity>().Property(e => e.MyDateColumn).HasColumnType("datetime2");

I eventually opted for the following:

public class MyDb : DbContext
{
    public override int SaveChanges()
    {
        UpdateDates();
        return base.SaveChanges();
    }

    private void UpdateDates()
    {
        foreach (var change in ChangeTracker.Entries<MyEntityBaseClass>())
        {
            var values = change.CurrentValues;
            foreach (var name in values.PropertyNames)
            {
                var value = values[name];
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date < SqlDateTime.MinValue.Value)
                    {
                        values[name] = SqlDateTime.MinValue.Value;
                    }
                    else if (date > SqlDateTime.MaxValue.Value)
                    {
                        values[name] = SqlDateTime.MaxValue.Value;
                    }
                }
            }
        }
    }
}

Solution 6 - C#

Sometimes EF does not know that is dealing with a computed column or a trigger. By design, those operations will set a value outside of EF after an insert.

The fix is to specify Computed in EF's edmx for that column in the StoreGeneratedPattern property.

For me it was when the column had a trigger which inserted the current date and time, see below in the third section.


Steps To Resolve

In Visual Studio open the Model Browser page then Model then Entity Types -> then

  1. Select the entity and the date time property
  2. Select StoreGeneratedPattern
  3. Set to Computed

EF Model Browser Model Entity Type dialog


For this situation other answers are workarounds, for the purpose of the column is to have a time/date specified when the record was created, and that is SQL's job to execute a trigger to add the correct time. Such as this SQL trigger:

DEFAULT (GETDATE()) FOR [DateCreated].

Solution 7 - C#

I ran into this and added the following to my datetime property:

 [Column(TypeName = "datetime2")]
 public DateTime? NullableDateTimePropUtc { get; set; }

Solution 8 - C#

If we dont pass a date time to date time field the default date {1/1/0001 12:00:00 AM} will be passed.

But this date is not compatible with entity frame work so it will throw conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

Just default DateTime.now to the date field if you are not passing any date .

movie.DateAdded = System.DateTime.Now

Solution 9 - C#

The easiest thing would be to change your database to use datetime2 instead of datetime. The compatibility works nicely, and you won't get your errors.

You'll still want to do a bunch of testing...

The error is probably because you're trying to set a date to year 0 or something - but it all depends on where you have control to change stuff.

Solution 10 - C#

I found this post trying to figure why I kept getting the following error which is explained by the other answers.

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

Use a nullable DateTime object.
public DateTime? PurchaseDate { get; set; }

If you are using entity framework Set the nullable property in the edmx file to True

[![Set the nullable property in the edmx file to True] 1]1

Solution 11 - C#

As andyuk has already pointed-out, this can happen when a NULL value is assigned to a non nullable DateTime field. Consider changing DateTime to DateTime? or Nullable<DateTime>. Bear in mind that, in case you are using a Dependency Property, should also make sure that your dependency property's type is also a nullable DateTime type.

Below is a real life example of an incomplete DateTime to DateTime? type adjustment that raises the odd behaviour

enter image description here

Solution 12 - C#

The Entity Framework 4 works with the datetime2 data type so in db the corresponding field must be datetime2 for SQL Server 2008.

To achive the solution there are two ways.

  1. To use the datetime data type in Entity Framwork 4 you have to switch the ProviderManifestToken in the edmx-file to "2005".
  2. If you set corresponding field as Allow Null (it converts it to NULLABLE) so then EF automatically uses date objects as datetime.

Solution 13 - C#

Add the below mentioned attribute on the property in your model class.

Attribute = [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
Reference = System.ComponentModel.DataAnnotations.Schema

Initially I forgot to add this attribute. So in my database the constraint was created like

ALTER TABLE [dbo].[TableName] ADD DEFAULT (getdate()) FOR [ColumnName]

and I added this attribute and updated my db then it got changed into

ALTER TABLE [dbo].[TableName] ADD CONSTRAINT [DF_dbo.TableName_ColumnName] DEFAULT (getdate()) FOR [ColumnName]

Solution 14 - C#

Created a base class based on @sky-dev implementation. So this can be easily applied to multiple contexts, and entities.

public abstract class BaseDbContext<TEntity> : DbContext where TEntity : class
{
    public BaseDbContext(string connectionString)
        : base(connectionString)
    {
    }
    public override int SaveChanges()
    {

        UpdateDates();
        return base.SaveChanges();
    }

    private void UpdateDates()
    {
        foreach (var change in ChangeTracker.Entries<TEntity>())
        {
            var values = change.CurrentValues;
            foreach (var name in values.PropertyNames)
            {
                var value = values[name];
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date < SqlDateTime.MinValue.Value)
                    {
                        values[name] = SqlDateTime.MinValue.Value;
                    }
                    else if (date > SqlDateTime.MaxValue.Value)
                    {
                        values[name] = SqlDateTime.MaxValue.Value;
                    }
                }
            }
        }
    }
}

Usage:

public class MyContext: BaseDbContext<MyEntities>
{

    /// <summary>
    /// Initializes a new instance of the <see cref="MyContext"/> class.
    /// </summary>
    public MyContext()
        : base("name=MyConnectionString")
    {
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="MyContext"/> class.
    /// </summary>
    /// <param name="connectionString">The connection string.</param>
    public MyContext(string connectionString)
        : base(connectionString)
    {
    }

     //DBcontext class body here (methods, overrides, etc.)
 }

Solution 15 - C#

I ran into this issue on a simple console app project and my quick solution is to convert any possible datetime2 dates to a nullable datetime by running this method:

static DateTime? ParseDateTime2(DateTime? date)
    {
        if (date == null || date.ToString() == "1/1/0001 12:00:00 AM")
        {
            return null;
        }
        else
        {
            return date;
        }
    }

This is certainly not a completely comprehensive method, but it worked for my needs and maybe it'll help others!

Solution 16 - C#

In my case we were casting a Date to a Datetime and we got this error. What happens is that Date has a "more programmer oriented" minimum of 01/01/0001, while Datetime is stuck at 1753

Combine that with a data collection error on our part, and you get your exception!

Solution 17 - C#

Sometimes it works fine on development machines and not in servers. In my case I had to put :

<globalization uiCulture="es" culture="es-CO" />

In the web.config file.

The timezone in the machine (Server) was right (to the CO locale) but the web app did not. This setting done and it worked fine again.

Off course, all dates had value.

:D

Solution 18 - C#

Adding this code to a class in ASP.NET worked fort me:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
}

Solution 19 - C#

I'm aware of this problem and you all should be too:

https://en.wikipedia.org/wiki/Year_2038_problem

In SQL a new field type was created to avoid this problem (datetime2).

This 'Date' field type has the same range values as a DateTime .Net class. It will solve all your problems, so I think the best way of solving it is changing your database column type (it won't affect your table data).

Solution 20 - C#

Check out the following two:

  1. This field has no NULL value. For example:

    public DateTime MyDate { get; set; }

Replace to:

public DateTime MyDate { get; set; }=DateTime.Now;

2) New the database again. For example:

db=new MyDb();

Solution 21 - C#

Problem with inherited datetime attribute

This error message is often showed when a non-nullable date field has value null at insert/update time. One cause can be inheritance.

If your date is inherit from a base-class and you don't make a mapping EF will not read it's value.

For more information: https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines

Solution 22 - C#

I saw this error when I wanted to edit a page usnig ASP.Net MVC. I had no problem while Creating but Updating Database made my DateCreated property out of range!

When you don't want your DateTime Property be Nullable and do not want to check if its value is in the sql DateTime range (and @Html.HiddenFor doesn't help!), simply add a static DateTime field inside related class (Controller) and give it the value when GET is operating then use it when POST is doing it's job:

public class PagesController : Controller
{
    static DateTime dateTimeField;
    UnitOfWork db = new UnitOfWork();

    // GET:
    public ActionResult Edit(int? id)
    {
        Page page = db.pageRepository.GetById(id);
        dateTimeField = page.DateCreated;
        return View(page);
    }

    // POST: 
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Page page)
    {
        page.DateCreated = dateTimeField;
        db.pageRepository.Update(page);
        db.Save();
        return RedirectToAction("Index");

    }
}

Solution 23 - C#

Check the req format in DB. eg my DB have Default value or Binding (((1)/(1))/(1900))

System.DateTime MyDate = new System.DateTime( 1900 ,1, 1);

enter image description here

Solution 24 - C#

For me I have had a Devexpress DateEdit component, which was binded to nullable datetime MSSQL column thru the Nullable model property. All I had to do was setting AllowNullInput = True on DateEdit. Having it "Default" caused that the date 1.1.0001 appeared - ONLY BEFORE leaving the DateEdit - and then I got this conversion error message because of subsequent instructions mentioned above.

Solution 25 - C#

In my case, when a NULL value is explicitly assigned for Nullable DateTime column and then you try to save the changes. This error will pop up.

Solution 26 - C#

you will have date column which was set to lesathan the min value of allowed dattime like 1/1/1001.

to overcome this issue you can set the proper datetime value to ur property adn also set another magical property like IsSpecified=true.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGerbrandView Question on Stackoverflow
Solution 1 - C#andyukView Answer on Stackoverflow
Solution 2 - C#marc_sView Answer on Stackoverflow
Solution 3 - C#GrahamView Answer on Stackoverflow
Solution 4 - C#JGilmartinView Answer on Stackoverflow
Solution 5 - C#sky-devView Answer on Stackoverflow
Solution 6 - C#ΩmegaManView Answer on Stackoverflow
Solution 7 - C#RogalaView Answer on Stackoverflow
Solution 8 - C#LijoView Answer on Stackoverflow
Solution 9 - C#Rob FarleyView Answer on Stackoverflow
Solution 10 - C#stinkView Answer on Stackoverflow
Solution 11 - C#Julio NobreView Answer on Stackoverflow
Solution 12 - C#Mahmut CView Answer on Stackoverflow
Solution 13 - C#Ajith ChandranView Answer on Stackoverflow
Solution 14 - C#dynamiclynkView Answer on Stackoverflow
Solution 15 - C#David Alan ConditView Answer on Stackoverflow
Solution 16 - C#ChrisView Answer on Stackoverflow
Solution 17 - C#Jaime Enrique Espinosa ReyesView Answer on Stackoverflow
Solution 18 - C#Howie KrauthView Answer on Stackoverflow
Solution 19 - C#marcolomewView Answer on Stackoverflow
Solution 20 - C#RainyTearsView Answer on Stackoverflow
Solution 21 - C#FrankyHollywoodView Answer on Stackoverflow
Solution 22 - C#mp3846View Answer on Stackoverflow
Solution 23 - C#Arsalan MaqsoodView Answer on Stackoverflow
Solution 24 - C#Jitka Darbie HübnerováView Answer on Stackoverflow
Solution 25 - C#Mukhtiar ZaminView Answer on Stackoverflow
Solution 26 - C#KoteshwarView Answer on Stackoverflow