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.
public class DateConvention : Convention
{
public DateConvention()
{
this.Properties<DateTime>()
.Configure(c => c.HasColumnType("datetime2").HasPrecision(3));
this.Properties<DateTime>()
.Where(x => x.GetCustomAttributes(false).OfType<DataTypeAttribute>()
.Any(a => a.DataType == DataType.Date))
.Configure(c => c.HasColumnType("date"));
}
}
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; }
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Birthday
{
[Key]
public int Id { get; set; }
[Column(TypeName = "date")]
public DateTime DateOfBirth { get; set; }
}