1

NB: this is a Sql-server Date datatype (Not DateTime, nor DateTime2, which most answers seem to focus on).

How to insert from EF ?

I tried as below, but I am stuck on the .NET side.

 TB_MyTable newEntity = new TB_MyTable()
{
    col1 = "abc",
    col2  = 123

    dtCol       = DateTime.MinValue,
    dateOnlyCol = ??? What goes here, range is '0001-01-01' to '9999-12-31'
};

TB_MyTable inserted = dbCtx.TB_MyTable.Add(newEntity);
int rowsAffected = dbCtx.SaveChanges();

Error on .SaveChanges() is:

{"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated."}

Please don't suggest to me to use string on the Right-Hand-Side, it doesn't work :P

joedotnot
  • 4,810
  • 8
  • 59
  • 91
  • What is the data type of dtCol column? The error seems to suggest that it is datetime (min value 1/1/1753) and you are trying to insert year 0001 into it. – Alex Apr 24 '19 at 09:09
  • Alex !! oops you are right. I was focusing on the wrong problem. dtCol is DateTime. And setting it to DateTime.MinValue was causing the error. I changed it to DateTime.Now and it went thru . For dateOnlyCol I can use DateTime.MinValue.Date and it works. I can accept your answer if you write it as such. – joedotnot Apr 24 '19 at 09:19
  • Glad it helped! I have added the answer. – Alex Apr 24 '19 at 10:12

1 Answers1

0

What is the data type of dtCol column?

The error seems to suggest that it is datetime (min value 1/1/1753) and you are trying to insert year 0001 (DateTime.MinValue) into it.

Additionally

Microsoft recommends DATETIME2 over DATETIME. For new projects I would suggest you use DATETIME2, not least for smoother .NET integration.

More details: DateTime2 vs DateTime in SQL Server

Alex
  • 4,885
  • 3
  • 19
  • 39