I am creating a database with entity framework migrations and I would like all DateTime fields to be created as DateTime and not the default DateTime2. I don't need the precision of DateTeim2 and I don't want the hassle of having to assign a value to every datetime field even if I don't need it.
Asked
Active
Viewed 1,258 times
2 Answers
1
As mentioned here, the MSDN documentation recommends using datetime2
. There is no further 'hassle' using it. However, if you absolutely must have the column as a datetime
type, then add this attribute to your property:
[Column(DbType="datetime")]
public DateTime? SomeDate { get; set; }
If you are now comfortable sticking with datetime2
and do not want to have to assign a value to the column, then make it nullable
. For example if your property looks like this:
public DateTime SomeDate { get; set; }
Then change it to this:
public DateTime? SomeDate { get; set; }
-
Is `Date` a new data type in the `.NET`? – Hamlet Hakobyan May 28 '14 at 13:18
-
Oops, well spotted. Fixed! – DavidG May 28 '14 at 13:19
0
Just set proper attribute. To map it to nullabe filed use property declaration as:
[Column(DbType="datetime NULL")]
public DateTime? YourDateTimeProp {get; set;}
Check the article for more information.

Hamlet Hakobyan
- 32,965
- 6
- 52
- 68