How to use Date Only as data type in Entity Framework

c# entity-framework orm sql-server type-conversion


When I use Entity Framework as an ORM, for each Date data type in my SQL Server DB it creates a DateTime data type y in my MVC project.

I mean, for each table in my DB, in my MVC project is auto-generated the code for this class using DateTime data type, but I don't need time, only the date.

So my question is: what can I do to declare this field as Date only data type or How is commonly handled this situation?.

public partial class Employee
    public int Id_Employee { get; set; }
    public string Name { get; set; }
    public string Last_Name { get; set; }
    public Nullable<System.DateTime> B_Date { get; set; }
    public Nullable<int> SSN_L4 { get; set; }
    public string Phone_N { get; set; }
    public string Adress_L1 { get; set; }
    public string Adress_City { get; set; }        
8/10/2015 6:45:23 AM

Accepted Answer

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)

Register this as before:

protected override void OnModelCreating(DbModelBuilder 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.

3/21/2015 1:40:04 PM

Popular Answer

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

public DateTime ReportDate { get; set; }

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow