2

I am using EF6 and trying to use Code First with Migrations against a SQL DB.

Is it possible using a data annotation in my POCO class to specify that the default value of a Boolean or Bit field should be true?

I know I could modify the data migrations code to add it to the specific migration class but would like to avoid that.

John S
  • 7,909
  • 21
  • 77
  • 145
  • Set the default value in the ctor. – Pawel Feb 11 '14 at 07:58
  • I would prefer to set it at the DB level because the DB will be used by other programs which I wont necessarily have control over the constructor of the classes used. – John S Feb 11 '14 at 15:02
  • 1
    Currently EF does not play well with the default values set by datatbase. When writing it will always saves the value th property was set to. – Pawel Feb 11 '14 at 15:55
  • I had the same problem, wanted to set default bool value to "false" for a "IsDeleted" column in my MyObject DB Table and use code first. In my Context class, method "protected override void OnModelCreating(DbModelBuilder modelBuilder)" I added this: modelBuilder.Entity().Property(p => p.IsDeleted).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed); The problem is that when my delete funcion was setting IsDeleted to "true" and saving, it would always save it as false. I had to remove the feature and change all my booleans to nullable bools... – firepol Oct 07 '14 at 11:12

1 Answers1

2

check this: How to set default value for POCO's in EF CF?

You can do this through Migration step.

public class Test
{
(...)

public bool TestProperty { get; set; }

(...)
}



public partial class AddTestClass : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "Test",
            c => new
                {
                    (...)
                    TestProperty = c => c.Boolean(nullable: false, defaultValue: false)
                    (...)
                })
            (...)
    }

    public overide void Down()
    {
        // Commands for when Migration is brought down
    }
}

`

Community
  • 1
  • 1
Gábor Plesz
  • 1,203
  • 1
  • 17
  • 28