Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First Date field creation

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?

like image 709
sfgroups Avatar asked Apr 14 '11 03:04

sfgroups


2 Answers

Try to use ColumnAttribute from System.ComponentModel.DataAnnotations (defined in EntityFramework.dll):

[Column(TypeName="Date")] public DateTime ReportDate { get; set; } 
like image 67
Ladislav Mrnka Avatar answered Sep 26 '22 12:09

Ladislav Mrnka


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.

like image 33
Richard Avatar answered Sep 25 '22 12:09

Richard