EF 7 set initial default value for DateTime column
You want to set the default value SQL, not a constant value:
entity.Property(e => e.ShipDate).HasDefaultValueSql("getutcdate()");
A more flexible solution using attributes for EF Core:
in your 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);
}
and create these classes:
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;
}
}
and custom attributes:
/// <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];
}
}
Then you will be able to decorate your table properties with any of these attributes (or make your own custom ones):
[DecimalPrecision(18, 9)]
[SqlDefaultValue("getutcdate()")]
[DataType("decimal(18,9)")]
@Michael Brown Thank you for these custom Attributes,
Update (EF Core 3.x): Starting with EF Core 3.0, the metadata API has changed again -
Relational()
extensions have been removed, and properties have been replaced withGet
andSet
extension methods, so now the code looks like this:credit for @Ivan Stoev in this answer https://stackoverflow.com/a/42467710/1475257
so whole code from @Michael Brown in NET Core and .NET 5 will be
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;
}
}
and Attributes
/// <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];
}
}