Entity Framework Cannot Save - Conversion Of Datetime2 To DateTime Failing

asp.net asp.net-mvc c# entity-framework sql

Question

I'm running into an issue where a few of my Entity Framework entities are failing to save data. The error I get is

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

I have a table called "Notes". It has a datetime field called "NoteDateTime". Here is a snippet of the SQL used to create the table. As you can see, the NoteDateTime field has nothing unusual about it.

CREATE TABLE [db].[Notes](
    [NoteID] [int] IDENTITY(1,1) NOT NULL,
    [NoteText] [varchar](8000) NULL,
    [NoteDateTime] [datetime] NULL,
    [IsReviewRequired] [bit] NULL,
    [ConvertToGlobal] [bit] NULL,
    [EmployeeID] [int] NULL,
    [EvaluationID] [int] NULL,
    [CustomerID] [int] NULL,
    [EmailID] [int] NULL,
    [AddedWhenMerged] [bit] NULL,
CONSTRAINT [PK_Notes] PRIMARY KEY CLUSTERED 
(
    [NoteID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

In my C# code, I populate a "Notes" entity and call the SaveChanges() method. The error occurs when I call SaveChanges().

dbContext.Notes.Add(new Note
{
    EvaluationID = evaluationId,
    CustomerID   = customerId,
    EmployeeID   = employeeId,
    NoteDateTime = DateTime.Now,
    NoteText     = noteText,
});

dbContext.SaveChanges();

I've read several stackoverflow threads and the advice was to ensure the proper date was being used and that the date should not be null. The date is not null and it is certainly within acceptable min/max limits. I also tried converting the type of the column to datetime2 in the database, but that didn't fix the issue. The bizarre thing is that this seems to be a recent issue. The only thing I can think of that changed in our environment is that we migrated our project to use MVC 4.

What can I do to troubleshoot this problem and get my Note entity to save properly?

1
2
9/13/2013 9:47:20 PM

Popular Answer

Julie Lerhman discusses this exact issue here (http://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Entity-Framework-Tips-and-Tricks), and trust me, she is the expert.

Myself, I'd make [NoteDateTime] nullable in your code like so

public DateTime? NoteDateTime { set; get; }
1
9/13/2013 11:39:56 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow