Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework and SqlDateTime overflow best practices

System.DateTime can take a wider range of values than SQL Server's DateTime. Hence there is class System.Data.SqlTypes.SqlDateTime which mimics the later.

Consequently I would have expected Entity Framework to choose SqlDateTime, but it didn't.

So my questions are...

What are the best practices to insure that your DateTime values will not cause problems when you try to save them to your database?

Is there any way of forcing EF to use SqlDateTime?

like image 979
Buh Buh Avatar asked Oct 15 '10 15:10

Buh Buh


1 Answers

There's a number of things you can do:

  • if you're using SQL Server 2008 or newer, you can use the DATE or DATETIME2 data types on the database which offer the same date range as .NET's DateTime

  • if you can't use those new data types, it will be up to you to handle some checking / validation on your date fields before things are being stored into the persistent store. EF EntityObject offers lots of ways to tap into the process of validating and saving objects - pick one approach that works for you

like image 127
marc_s Avatar answered Sep 21 '22 02:09

marc_s