is there "elegant" way to give specific property a default value ?
Maybe by DataAnnotations, something like :
[DefaultValue("true")]
public bool Active { get; set; }
Thank you.
You can do it by manually edit code first migration:
public override void Up()
{
AddColumn("dbo.Events", "Active", c => c.Boolean(nullable: false, defaultValue: true));
}
It's been a while, but I'm leaving a note for others. I achieved what was needed with an attribute and decorated my model class fields with that attribute as I wanted.
[SqlDefaultValue("getutcdate()")]
public DateTime CreatedDateUtc { get; set; }
Got the help of these 2 articles:
What I did:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
public SqlDefaultValueAttribute(string defaultValue)
{
DefaultValue = defaultValue;
}
public string DefaultValue { get; set; }
}
modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));
private void SetAnnotatedColumn(ColumnModel col)
{
AnnotationValues values;
if (col.Annotations.TryGetValue("SqlDefaultValue", out values))
{
col.DefaultValueSql = (string)values.NewValue;
}
}
Then in the Migration Configuration constructor, register the custom SQL generator.
SetSqlGenerator("System.Data.SqlClient", new CustomMigrationSqlGenerator());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With