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
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.
Beside using ColumnAttribute
you can also create a custom attribute convention for the DataTypeAttribute
:
public class DataTypePropertyAttributeConvention : AttributeConfigurationConvention<PropertyInfo, PrimitivePropertyConfiguration, DataTypeAttribute>
{
public override void Apply(PropertyInfo memberInfo, PrimitivePropertyConfiguration configuration, DataTypeAttribute attribute)
{
if (attribute.DataType == DataType.Date)
{
configuration.ColumnType = "Date";
}
}
}
Just register the convention in your OnModelCreating method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Add(new DataTypePropertyAttributeConvention());
}
If you prefer not to decorate your classes with attributes, you can set this up in the DbContext
's OnModelCreating
like this:
public class DatabaseContext: DbContext
{
// DbSet's
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// magic starts
modelBuilder.Entity<YourEntity>()
.Property(e => e.ReportDate)
.HasColumnType("date");
// magic ends
// ... other bindings
}
}
Try to use ColumnAttribute
from System.ComponentModel.DataAnnotations
(defined in EntityFramework.dll):
[Column(TypeName="Date")]
public DateTime ReportDate { get; set; }
the Best Way it using The
[DataType(DataType.Date)]
public DateTime ReportDate { get; set; }
but you must using the EntityFramework v 6.1.1
This is just an enhancement for the most up-voted answer by @LadislavMrnka on this question
if you have a lot of Date
columns, then you can create custom attribute and then use it when ever you want, this will produce more clean code in the Entity classes
public class DateColumnAttribute : ColumnAttribute
{
public DateColumnAttribute()
{
TypeName = "date";
}
}
Usage
[DateColumn]
public DateTime DateProperty { get; set; }