Click here to Skip to main content
15,867,979 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi I was trying to add data to table and it was working but now it gives this error
datetime2 data type to a datetime data type resulted in an out-of-range value


Here is my code ;
C#
var itemSelectedName = Db.Topics.FirstOrDefault(p => p.Id == TopicId);
var itemMap = Db.Reeves.FirstOrDefault(p=> p.Member.Id == CurrentMember.Id);
var itemReeve = Db.Reeves.FirstOrDefault(p => p.Member.Id == CurrentMember.Id);

            var item = new Problem
            {
                Name = input.Name,
                Text = input.Info,
                Topic = itemSelectedName,
                WhoIs = itemMember,
                Province = itemMap.Province,
                District = itemMap.District,
                Town = itemMap.Town,
                Reeve=itemReeve,
                Created=DateTime.Now,
                Solved = false,
                Read=false

            };
            Db.Problems.Add(item);
            Db.SaveChanges();


this was working without any problem till today. I dont know what happend.How to fix this ?
Posted
Updated 15-Aug-15 0:30am
v3
Comments
Patrice T 15-Aug-15 6:36am    
Where is the error ?
What is the format of DateTime and DateTime2 ?
Where is the code that convert ?

1 solution

Based on the message it sounds that your database has datetime2 field with a value that is smaller than the minimum value of SqlDateTime in .Net.

From SqlDateTime.MinValue Field[^]
"The minimum valid date for a SqlDateTime structure is January 1, 1753."

So if the database contains a value smaller than that, conversion would fail.
 
Share this answer
 
Comments
Ger Hayden 4-May-22 9:53am    
This solution does not explain how a date value of now i.e. some time in the 21st century is not mapped properly resulting in the SaveChanges() substituting a value of '0001-01-01' during the generation of the SQL.
Wendelius 4-May-22 11:13am    
As far as I can see, the problem wasn't in the generation of the SQL, instead it happened while reading from the database.

As the error message states, the problem occurred in conversion from datetime2 (data type in SQL Server) to datetime (type in C#). So if that's the case, the problem wasn't in inserting but in reading.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900