I am using Entity Framework Code First method to create my database table. The following code
creates a DATETIME
column in the database, but I want to create a DATE
column.
[DataType(DataType.Date)]
[DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime ReportDate { get; set; }
How can I create a column of type DATE
, during table creation?
Try to use
ColumnAttribute
fromSystem.ComponentModel.DataAnnotations
(defined in EntityFramework.dll):I use following
With Entity Framework 6 & SQL Server Express 2012 - 11.0.2100.60 (X64). It works perfectly and generates time/date column types in sql server
the Best Way it using The
but you must using the EntityFramework v 6.1.1
The EF6 version of David Roth's answer is as follows:
Register this as before:
This has the same outcome as Tyler Durden's approach, except that it's using an EF base class for the job.
If you prefer not to decorate your classes with attributes, you can set this up in the
DbContext
'sOnModelCreating
like this:I found this works in EF6 nicely.
I created a convention for specifying my data types. This convention changes the default DateTime data type in the database creation from datetime to datetime2. It then applies a more specific rule to any properties that I have decorated with the DataType(DataType.Date) attribute.
Then register then convention in your context:
Add the attribute to any DateTime properties that you wish to be date only: