Entity Framework Code First Date field creation
Try to use ColumnAttribute
from System.ComponentModel.DataAnnotations
(defined in EntityFramework.dll):
[Column(TypeName="Date")]
public DateTime ReportDate { get; set; }
The EF6 version of David Roth's answer is as follows:
public class DataTypePropertyAttributeConvention
: PrimitivePropertyAttributeConfigurationConvention<DataTypeAttribute>
{
public override void Apply(ConventionPrimitivePropertyConfiguration configuration,
DataTypeAttribute attribute)
{
if (attribute.DataType == DataType.Date)
{
configuration.HasColumnType("Date");
}
}
}
Register this as before:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Add(new DataTypePropertyAttributeConvention());
}
This has the same outcome as Tyler Durden's approach, except that it's using an EF base class for the job.
I use following
[DataType(DataType.Time)]
public TimeSpan StartTime { get; set; }
[DataType(DataType.Time)]
public TimeSpan EndTime { get; set; }
[DataType(DataType.Date)]
[Column(TypeName = "Date")]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[Column(TypeName = "Date")]
public DateTime EndDate { get; set; }
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