33

How can I set the default value using EntityFramework Code First FluentAPI for bool property?

Something like:

Property(l => l.PropertyFlag).HasColumnType("bit").DefaultValue(1);
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Tony Bao
  • 922
  • 2
  • 12
  • 23
  • possible duplicate of [How can set a default value constraint with Entity Framework 6 Code First?](http://stackoverflow.com/questions/20136504/how-can-set-a-default-value-constraint-with-entity-framework-6-code-first) – Colin Nov 25 '13 at 20:10
  • There should be some kind of solution for this issue, not just simple "No". I am talking all possible solutions. – Tony Bao Nov 25 '13 at 21:32
  • 1
    Sorry, I hadn't realised that. I thought you were looking for how to set the default value using EntityFramework Code First FluentAPI for bool property. How foolish of me ;-) – Colin Nov 26 '13 at 13:40

4 Answers4

31

Good news, code first now supports this. In the "Up()" method of the generated migration, specify a default with the following syntax:

AddColumn("[table name]", "[column name]", c => c.Boolean(nullable: false, defaultValue: false));

MSDN for "AddColumn" method

htxryan
  • 2,871
  • 2
  • 21
  • 21
  • 1
    @joelmdev Added a link to MSDN documentation – htxryan Mar 12 '14 at 21:15
  • 2
    This is only an Up migration. The OP is asking for how to set defaults at time of insert. Behind-the-scenes, EF maps every property in the POCO into the Insert statement as a NULL if the C# property is null. For value types, it inserts the value types default value. Useful info, though! – John Zabroski Sep 04 '14 at 03:20
  • 3
    The downside is that you have to remember to re-add this peice of code if you re-scafold your migration. Hopefully they will support this function in Fluent Api soon. – FatAlbert Apr 21 '15 at 08:43
10

I'm not sure about a fluent way, but you can simply set the property in a parameterless constructor...

public class MyTable
{
    public MyTable()
    {
        CanSetDefault = true;
    }

    public bool CanSetDefault {get; set; }
}

Update

A quick google suggests it is not possible using the fluent api...
http://social.msdn.microsoft.com/Forums/en-US/ad854e28-02f5-451b-9000-c8bcb1355d0b/codefirst-ctp5-and-default-values?forum=adonetefx

NinjaNye
  • 7,046
  • 1
  • 32
  • 46
  • 2
    Good suggestion, but doesn't work for DateTime.Now which is used for CreatedOn fields, as you will have clock drift from the time the class instance is constructed to when it is inserted. This would lead to some hard-to-debug code based on audit logs. – John Zabroski Sep 04 '14 at 03:21
  • This is now being worked on for EF7 and available in pre-release https://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/2929682-support-database-default-values-in-code-first – James Reategui Feb 18 '15 at 17:57
  • This only works for entries added with this. If you have existing entries, and you are adding a column to your schema, this doesn't work. – Warrick May 11 '17 at 03:03
2

Another option here is to override the default SqlServerMigrationSqlGenerator class with your own. You can then inject certain things you want to happen in the Generate method (for example, default values). The nice things with this is that you can also use this in other applications as it is pretty generic. Here is a good explanation on it.

 internal class CustomSqlServerMigrationSqlGenerator : SqlServerMigrationSqlGenerator
{

    protected override void Generate(AddColumnOperation addColumnOperation)
    {
        SetCreatedUtcColumn(addColumnOperation.Column);

        base.Generate(addColumnOperation);
    }

    protected override void Generate(CreateTableOperation createTableOperation)
    {
        SetCreatedUtcColumn(createTableOperation.Columns);

        base.Generate(createTableOperation);
    }


    private static void SetCreatedUtcColumn(IEnumerable<ColumnModel> columns)
    {
        foreach (var columnModel in columns)
        {
            SetCreatedUtcColumn(columnModel);
        }
    }

    private static void SetCreatedUtcColumn(PropertyModel column)
    {
        if (column.Name == "CreatedUtc")
        {
            column.DefaultValueSql = "GETUTCDATE()";
        }
    }


}
gcoleman0828
  • 1,541
  • 3
  • 30
  • 49
  • Full explanation: https://andy.mehalick.com/2014/02/06/ef6-adding-a-created-datetime-column-automatically-with-code-first-migrations/ – jwatts1980 Sep 24 '17 at 05:58
0

Since EF doesn't have the functions I need, such as default values and unique key as foreign keys, we have to change the ORM from EF to NHibernate. It seems to me that NHibernate has more functions than EF 6.X.

Tony Bao
  • 922
  • 2
  • 12
  • 23