Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF returns "Cannot Insert NULL" ... But column defines a default value [duplicate]

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.

like image 429
marino-krk Avatar asked Jun 23 '26 02:06

marino-krk


2 Answers

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));
} 
like image 154
gdbdable Avatar answered Jun 26 '26 15:06

gdbdable


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:

  • EF on CodePlex
  • Andy Mehalick blog

What I did:

Define Attribute

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
    public SqlDefaultValueAttribute(string defaultValue)
    {
        DefaultValue = defaultValue;
    }

    public string DefaultValue { get; set; }
}

In the "OnModelCreating" of the context

modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));

In the custom SqlGenerator

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());
like image 28
ravinsp Avatar answered Jun 26 '26 15:06

ravinsp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!