6

Tôi sử dụng mã di chuyển đầu tiên và tự động của mã EF. Tôi muốn thêm một cột mới vào mô hình của tôi - một cột boolean để trình bày "hoạt động" (đúng) hoặc "không hoạt động" (sai). Làm cách nào để thêm cột này và đặt giá trị mặc định ("true") cho các hàng đã có trong DB - với các lần di chuyển tự động?EF - Giá trị mặc định cho cột mới với di chuyển tự động

Trả lời

6

Tamar, bạn cần thiết lập giá trị mặc định, xem mẫu tiếp theo:

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 sẽ hỗ trợ giá trị mặc định từ mô hình http://data.uservoice.com/forums/72025-entity-framework-feature -số đề xuất/đề xuất/2929682-hỗ trợ-cơ sở dữ liệu-mặc định-giá trị-trong-mã-đầu tiên – fuchs777

Các vấn đề liên quan