实体框架代码第一个日期字段创建 [英] Entity Framework Code First Date field creation

查看:92
本文介绍了实体框架代码第一个日期字段创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework Code First方法来创建我的数据库表。以下代码
在数据库中创建一个 DATETIME 列,但是我想创建一个 DATE 列。

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; }

如何创建一个类型为 DATE ,在创建表时?

How can I create a column of type DATE, during table creation?

推荐答案

David Roth的EF6版本的答案如下:

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");
        }
    }
}

注意: / p>

Register this as before:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Conventions.Add(new DataTypePropertyAttributeConvention());
}

与Tyler Durden的做法相同,除了使用EF工作的基础类。

This has the same outcome as Tyler Durden's approach, except that it's using an EF base class for the job.

这篇关于实体框架代码第一个日期字段创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆