13

I have a class that looks like this:

[Table("Subscribers", Schema = "gligoran")]
public class Subscriber
{
    [Key]
    public string Email { get; set; }

    [Required]
    [DefaultValue(true)]
    public bool Enabled { get; set; }
}

When creating a migration to include this class I get:

public partial class AddSubscriberClass : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "gligoran.Subscribers",
            c => new
                {
                    Email = c.String(nullable: false, maxLength: 128),
                    Enabled = c.Boolean(nullable: false),
                })
            .PrimaryKey(t => t.Email);

    }

    public override void Down()
    {
        DropTable("gligoran.Subscribers");
    }
}

I'd like the Enabled line to look like this:

Enabled = c.Boolean(nullable: false, defaultValue: true),

Of course I can do this myself, but I'm just asking if there's a way to make Entity Framework do it automatically.

I'm using the latest Entity Framework 5 RC (5.0.0-rc.net40).

gligoran
  • 3,267
  • 3
  • 32
  • 47

2 Answers2

11

EF doesn't use DefaultValue attribute at all = it is not part of the model so migrations don't see it. You can propose support of this annotation on Data UserVoice.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I guess manually is the only was. Thanks for the UserVoice link, though. I have a couple of ideas for them. – gligoran Jul 19 '12 at 20:40
  • 2
    Actually MS today released [EF as open source](http://entityframework.codeplex.com/) so you can even try it yourselves ;) – Ladislav Mrnka Jul 19 '12 at 20:43
  • Nice! I was searching for it the other day and came to the conclusion that it's not open. I like the new(ish) Microsoft open policy. – gligoran Jul 19 '12 at 21:31
  • 2
    Here's an existing [User Voice suggestion for this feature](http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/2929682-support-database-default-values-in-code-first). – Bart Verkoeijen Oct 27 '13 at 14:32
7

As an Extra to Ladislav's Comment. Which is correct. you cant do it in the model. IF you wanted to use code based migrations. Ie using PM commandlet Add-Migration / Update Database, then this approach introduces a generated class into the process. Then you can have defaults . See the classes that Derive from DBMigrations. see http://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigration.addcolumn%28v=vs.103%29.aspx You can specific Column builder Lamda expressions. This allows defaults.

namespace MigrationsDemo.Migrations
{
  using System;
  using System.Data.Entity.Migrations;

public partial class SomeClassThatisATable : DbMigration
{
    public override void Up()
    {
        AddColumn("MyTable", "MyColumn", c => c.String( defaultvalue:"Mydefault"  ));
    }
phil soady
  • 11,043
  • 5
  • 50
  • 95