Entity Framework Code First Date field creation

后端 未结 8 2291
情歌与酒
情歌与酒 2020-11-30 23:13

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

8条回答
  •  没有蜡笔的小新
    2020-11-30 23:50

    The EF6 version of David Roth's answer is as follows:

    public class DataTypePropertyAttributeConvention 
        : PrimitivePropertyAttributeConfigurationConvention
    {
        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.

提交回复
热议问题