简体   繁体   中英

conversion of a datetime2 data type to a datetime data type error with EF Code first?

I'm using EF Code first with my asp.net mvc application. here is my code:

Request.RequestDate = DateTime.Now;

the type of RequestDate is datetime in my database. and this is error that occurred when i use the above code::

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

please help me. thanks.

Edit:

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

The issue is that you are trying to save a value that cannot fit in a SQL datetime column. the answer givin here will stop the conversion from failing.

or in your Database change the columns to be type datetime2. I don't exactly know why they code first is generating datetime columns instead of datetime2

Here is an example to explicitly map your Datetime columns to datetime2 in SQL

Using DateTime properties in Code-First Entity Framework and SQL Server

On my side it was because the datetime was not nullable and in some situation the field was not initialized in the constructor. I solved this by setting my field as nullable

public DateTime? MyDate { get; set; }

Another solution would be to initialize the field in the constructor no matter what.

    --in your sql script:
        create table tablename(mydate DateTime not null default GETDATE())


        //in your c# object:
        public class tablename
        {
          public string mydate {get; set; } = null;
        }

        //in your C# method using EF:
        private async Task mymethod()
        {
            DateTime myDateTime = DateTime.Now;
            string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
            dbContext.tablename.add(new tablenam{mydate = sqlFormattedDate });
            await dbContext.SaveChangesAsync();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM