6

Ich verwende EF-Code erste und automatische Migrationen. Ich möchte meinem Modell eine neue Spalte hinzufügen - eine boolesche Spalte, die "aktiv" (true) oder "inaktiv" (false) darstellt. Wie kann ich diese Spalte hinzufügen und einen Standardwert ("true") für die bereits im DB vorhandenen Zeilen setzen - bei automatischen Migrationen?EF - Standardwert für neue Spalte mit automatischer Migration

Antwort

6

Tamar, müssen Sie festlegen Standardwert, siehe nächstes Beispiel:

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

    public partial class AddPostClass : DbMigration 
    { 
     public override void Up() 
     { 
      CreateTable( 
       "dbo.Posts", 
       c => new 
        { 
         PostId = c.Int(nullable: false, identity: true), 
         Title = c.String(maxLength: 200), 
         Content = c.String(), 
         BlogId = c.Int(nullable: false), 
        }) 
       .PrimaryKey(t => t.PostId) 
       .ForeignKey("dbo.Blogs", t => t.BlogId, cascadeDelete: true) 
       .Index(t => t.BlogId) 
       .Index(p => p.Title, unique: true); 

      AddColumn("dbo.Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3)); 
     } 

     public override void Down() 
     { 
      DropIndex("dbo.Posts", new[] { "Title" }); 
      DropIndex("dbo.Posts", new[] { "BlogId" }); 
      DropForeignKey("dbo.Posts", "BlogId", "dbo.Blogs"); 
      DropColumn("dbo.Blogs", "Rating"); 
      DropTable("dbo.Posts"); 
     } 
    } 
} 
+0

EF 7 wird die Standardwerte aus dem Modell unterstützen http://data.uservoice.com/forums/72025-entity-framework-feature -suggestions/suggestions/2929682-support-database-default-values-in-code-zuerst – fuchs777