EF 7设置DateTime列的初始默认值

本文关键字:默认值 设置 DateTime EF | 更新日期: 2023-09-27 18:08:12

我需要能够设置DateTime列的初始值。

当我指定" getutdate()或DateTime。UtcNow

entity.Property(e => e.ShipDate).DefaultValue("getutcdate()")
entity.Property(e => e.ShipDate).DefaultValue(DateTime.UtcNow)

,然后运行dnx . ef migration add InitialMigration EF生成一个迁移快照:

b.Property<DateTime?>("ShipDate")
  .Required()
  .Annotation("Relational:ColumnDefaultValue", "getutcdate()")
  .Annotation("Relational:ColumnDefaultValueType", "System.String");

当我使用DateTime.UtcNow…

b.Property<DateTime?>("ShipDate")
  .Annotation("Relational:ColumnDefaultValue", "635754129448768827")
  .Annotation("Relational:ColumnDefaultValueType", "System.DateTime");

和初始迁移:

ShipDate = table.Column(
  type: "datetime2", 
  nullable: false, 
  defaultValue: "getutcdate()"),

当我使用DateTime.UtcNow…

ShipDate = table.Column(
  type: "datetime2", 
  nullable: true, 
  defaultValue: new DateTime(2015, 8, 17, 12, 55, 44, 876, DateTimeKind.Unspecified)),

看起来它必须工作,但是当我向表中插入数据时,列的默认值是创建时间戳的'instant'。

我错过了什么吗?

也,因为在相同的静脉,如何指定身份种子在EF7?

感谢

生成sql脚本后,使用这两个选项,我得到:

如果使用" getdate () ":

[ShipDate] datetime2 DEFAULT 'getutcdate()',

因为引号

不起作用

或者使用DateTime.utcNow:

[ShipDate] datetime2 DEFAULT '2015-08-17 12:55:44.8760000'

解释了我得到的静态值。

我想我能应付得来。这是一个bug还是有正确的方法?由于

EF 7设置DateTime列的初始默认值

您希望设置默认值SQL,而不是常量值:

entity.Property(e => e.ShipDate).HasDefaultValueSql("getutcdate()");

使用EF Core属性的更灵活的解决方案:

在你的DbContext:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    // Add your customizations after calling base.OnModelCreating(builder);
    CustomDataTypeAttributeConvention.Apply(builder);
    DecimalPrecisionAttributeConvention.Apply(builder);
    SqlDefaultValueAttributeConvention.Apply(builder);
}

并创建这些类:

public static class SqlDefaultValueAttributeConvention
{
    public static void Apply(ModelBuilder builder)
    {
        ConventionBehaviors
            .SetSqlValueForPropertiesWithAttribute<SqlDefaultValueAttribute>(builder, x => x.DefaultValue);
    }
}
public static class DecimalPrecisionAttributeConvention
{
    public static void Apply(ModelBuilder builder)
    {
        ConventionBehaviors
            .SetTypeForPropertiesWithAttribute<DecimalPrecisionAttribute>(builder,
                x => $"decimal({x.Precision}, {x.Scale})");
    }
}
public class CustomDataTypeAttributeConvention
{
    public static void Apply(ModelBuilder builder)
    {
        ConventionBehaviors
            .SetTypeForPropertiesWithAttribute<DataTypeAttribute>(builder,
                x => x.CustomDataType);
    }
}
public static class ConventionBehaviors
{
    public static void SetTypeForPropertiesWithAttribute<TAttribute>(ModelBuilder builder, Func<TAttribute, string> lambda) where TAttribute : class
    {
        SetPropertyValue<TAttribute>(builder).ForEach((x) => {
            x.Item1.Relational().ColumnType = lambda(x.Item2);
        });
    }
    public static void SetSqlValueForPropertiesWithAttribute<TAttribute>(ModelBuilder builder, Func<TAttribute, string> lambda) where TAttribute : class
    {
        SetPropertyValue<TAttribute>(builder).ForEach((x) =>
        {
            x.Item1.Relational().DefaultValueSql = lambda(x.Item2);
        });
    }
    private static List<Tuple<IMutableProperty, TAttribute>> SetPropertyValue<TAttribute>(ModelBuilder builder) where TAttribute : class
    {
        var propsToModify = new List<Tuple<IMutableProperty, TAttribute>>();
        foreach (var entity in builder.Model.GetEntityTypes())
        {
            var properties = entity.GetProperties();
            foreach (var property in properties)
            {
                var attribute = property.PropertyInfo
                    .GetCustomAttributes(typeof(TAttribute), false)
                    .FirstOrDefault() as TAttribute;
                if (attribute != null)
                {
                    propsToModify.Add(new Tuple<IMutableProperty, TAttribute>(property, attribute));
                }
            }
        }
        return propsToModify;
    }
}

和自定义属性:

/// <summary>
/// Set a default value defined on the sql server
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
    /// <summary>
    /// Default value to apply
    /// </summary>
    public string DefaultValue { get; set; }
    /// <summary>
    /// Set a default value defined on the sql server
    /// </summary>
    /// <param name="value">Default value to apply</param>
    public SqlDefaultValueAttribute(string value)
    {
        DefaultValue = value;
    }
}
/// <summary>
/// Set the decimal precision of a decimal sql data type
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class DecimalPrecisionAttribute : Attribute
{
    /// <summary>
    /// Specify the precision - the number of digits both left and right of the decimal
    /// </summary>
    public int Precision { get; set; }
    /// <summary>
    /// Specify the scale - the number of digits to the right of the decimal
    /// </summary>
    public int Scale { get; set; }
    /// <summary>
    /// Set the decimal precision of a decimal sql data type
    /// </summary>
    /// <param name="precision">Specify the precision - the number of digits both left and right of the decimal</param>
    /// <param name="scale">Specify the scale - the number of digits to the right of the decimal</param>
    public DecimalPrecisionAttribute(int precision, int scale)
    {
        Precision = precision;
        Scale = scale;
    }
    public DecimalPrecisionAttribute(int[] values)
    {
        Precision = values[0];
        Scale = values[1];
    }
}

然后你就可以用这些属性来装饰你的表属性了(或者自定义):

[DecimalPrecision(18, 9)][SqlDefaultValue("getutcdate()")][DataType("decimal(18,9)")]

@Michael Brown感谢您提供这些自定义属性,

更新(EF Core 3.x):从EF Core 3.0开始,元数据API再次发生变化- Relational()扩展已被删除,属性已被GetSet扩展方法所取代,所以现在代码看起来像这样:

这个答案中@Ivan Stoev的功劳https://stackoverflow.com/a/42467710/1475257

. NET Core@Michael Brown的全部代码。. NET 5将是

Convensions


    public static class DecimalPrecisionAttributeConvention
    {
        public static void Apply(ModelBuilder builder)
        {
            ConventionBehaviors
                .SetTypeForPropertiesWithAttribute<DecimalPrecisionAttribute>(builder,
                    x => $"decimal({x.Precision}, {x.Scale})");
        }
    }
    public class CustomDataTypeAttributeConvention
    {
        public static void Apply(ModelBuilder builder)
        {
            ConventionBehaviors
                .SetTypeForPropertiesWithAttribute<DataTypeAttribute>(builder,
                    x => x.CustomDataType);
        }
    }
    public static class ConventionBehaviors
    {
        public static void SetTypeForPropertiesWithAttribute<TAttribute>(ModelBuilder builder, Func<TAttribute, string> lambda) where TAttribute : class
        {
            SetPropertyValue<TAttribute>(builder).ForEach((x) =>
            {
                x.Item1.SetColumnType(lambda(x.Item2));
            });
        }
        public static void SetSqlValueForPropertiesWithAttribute<TAttribute>(ModelBuilder builder, Func<TAttribute, string> lambda) where TAttribute : class
        {
            SetPropertyValue<TAttribute>(builder).ForEach((x) =>
            {
                x.Item1.SetDefaultValueSql(lambda(x.Item2));
            });
        }
        private static List<Tuple<IMutableProperty, TAttribute>> SetPropertyValue<TAttribute>(ModelBuilder builder) where TAttribute : class
        {
            var propsToModify = new List<Tuple<IMutableProperty, TAttribute>>();
            foreach (var entity in builder.Model.GetEntityTypes())
            {
                var properties = entity.GetProperties();
                foreach (var property in properties)
                {
                    var attribute = property.PropertyInfo
                        .GetCustomAttributes(typeof(TAttribute), false)
                        .FirstOrDefault() as TAttribute;
                    if (attribute != null)
                    {
                        propsToModify.Add(new Tuple<IMutableProperty, TAttribute>(property, attribute));
                    }
                }
            }
            return propsToModify;
        }
    }

属性
    /// <summary>
    /// Set a default value defined on the sql server
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public class SqlDefaultValueAttribute : Attribute
    {
        /// <summary>
        /// Default value to apply
        /// </summary>
        public string DefaultValue { get; set; }
        /// <summary>
        /// Set a default value defined on the sql server
        /// </summary>
        /// <param name="value">Default value to apply</param>
        public SqlDefaultValueAttribute(string value)
        {
            DefaultValue = value;
        }
    }
    /// <summary>
    /// Set the decimal precision of a decimal sql data type
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public class DecimalPrecisionAttribute : Attribute
    {
        /// <summary>
        /// Specify the precision - the number of digits both left and right of the decimal
        /// </summary>
        public int Precision { get; set; }
        /// <summary>
        /// Specify the scale - the number of digits to the right of the decimal
        /// </summary>
        public int Scale { get; set; }
        /// <summary>
        /// Set the decimal precision of a decimal sql data type
        /// </summary>
        /// <param name="precision">Specify the precision - the number of digits both left and right of the decimal</param>
        /// <param name="scale">Specify the scale - the number of digits to the right of the decimal</param>
        public DecimalPrecisionAttribute(int precision, int scale)
        {
            Precision = precision;
            Scale = scale;
        }
        public DecimalPrecisionAttribute(int[] values)
        {
            Precision = values[0];
            Scale = values[1];
        }
    }