2012-02-10 54 views
3

我的模型以前沒有任何DataNotations,但我最近改變了這種情況,對某些屬性應用[必需的]。當發生這種情況時,我的遷移代碼開始引發異常,如:EF 4.1代碼優先 - 使用[必需的]屬性更新

無法應用待定更改,因爲已禁用自動遷移 。要啓用自動遷移,請確保將 DbMigrationsConfiguration.AutomaticMigrationsEnabled設置爲true。

我假定需要做一些明確的遷移行爲。請澄清。

編輯:AutomaticMigrationsEnabled = true對我來說不是選項,我很有趣如何使用一些遷移腳本來實現它。

回答

2

添加配置類擴展DbMigrationsConfiguration並設置AutomaticMigrationsEnabled爲true,樣品類是這樣的

namespace yournamespace 
{ 
    using System; 
    using System.Data.Entity; 
    using System.Data.Entity.Migrations; 
    using System.Linq; 

     internal sealed class Configuration : DbMigrationsConfiguration<YourDbContext> 
     { 
      public Configuration() 
      { 
       AutomaticMigrationsEnabled = true; 
       AutomaticMigrationDataLossAllowed = true; 
      } 


     } 
    } 

則配置類添加到DbMigrator實例如下

namespace yournamespace 
{ 
    public class YourDataMigrator 
    { 
     public void MigrateData() 
     { 
      DbMigrationsConfiguration configuration=new Configuration(); 
      DbMigrator dbMigrator = new DbMigrator(configuration); 

      try 
      { 
       dbMigrator.Update(); 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 

     } 
    } 

} 

我認爲這會解決你的問題

+0

如何做到這一點,沒有AutomaticMigrationsEnabled = true選項? – 2012-02-10 08:55:05

0

不知道我是否在這裏相同的網頁,但我認爲這就是你問。我有AutomaticMigrations設置爲false:

public Configuration() 
{ 
     AutomaticMigrationsEnabled = false; 
} 

我有一個郵政類設置是這樣的:

public class Post 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    [Required] 
    public DateTime DateCreated { get; set; } 
    public string Content { get; set; } 
    public string Tags { get; set; } 
    public ICollection<Comment> Comments { get; set; } 
} 

它已經產生,但後來我意識到,由於某種原因,我想需要稱號。

public class Post 
{ 
    public int Id { get; set; } 
    [Required] 
    public string Title { get; set; } 
    [Required] 
    public DateTime DateCreated { get; set; } 
    public string Content { get; set; } 
    public string Tags { get; set; } 
    public ICollection<Comment> Comments { get; set; } 
} 

我作出改變,做一個快速的構建,然後從PM控制檯I型:

添加遷移AddPostAnnotation(名稱可以是任何你想要的)

此生成此文件:

public partial class AddPostAnnotations : DbMigration 
{ 
    public override void Up() 
    { 
     AlterColumn("dbo.Posts", "Title", c => c.String(nullable: false)); 
    } 

    public override void Down() 
    { 
     AlterColumn("dbo.Posts", "Title", c => c.String()); 
    } 
} 

一旦在這裏,我只是從PM控制檯運行更新數據庫,併發送更改。