2011-06-24 64 views
0

我有一個優先級類,它有一個日期時間列。此列在SQL中具有默認值(在EF生成數據庫和表後,我將默認值CreatedDate更改爲getdate())。所以,我只是想插入優先的其他列,但EF不允許我並給出了這個錯誤:EF - 代碼優先 - SQL默認值getdate()給出錯誤

System.InvalidOperationException: The model backing the 'ToDoModel' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

public class Priority 
{ 

    public int ID { get; set; }   
    public string Name { get; set; } 
    public string Color { get; set; } 
    public string Image { get; set; }  
    public DateTime CreatedDate { get; set; } 

} 

public class ToDoModel:DbContext 
{ 

    public ToDoModel() : base("ToDoList.ConnectionString") {   
    } 

    public DbSet<Priority> Priorites { get; set; } 

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    {   

     modelBuilder.Entity<Priority>().MapSingleType().ToTable("tblPriority"); 
     modelBuilder.Entity<Priority>().HasKey(x => x.ID); 
     modelBuilder.Entity<Priority>().Property(x => x.CreatedDate).StoreGeneratedPattern = StoreGeneratedPattern.Computed; 

     base.OnModelCreating(modelBuilder); 
    } 

} 


[TestMethod] 
    public void CanAddPriority() 
    { 
     var priority = new Priority(); 
     priority.Color = "red"; 
     priority.Image = "critical.jpg"; 
     priority.Name = "Critical"; 
     db.Priorites.Add(priority);   
     db.SaveChanges(); 
     Assert.IsTrue(priority.ID > 0); 

    } 

回答

2

OnModelCreating方法,我設置modelBuilder.IncludeMetadataInDatabase爲false,現在一切都workink罰款。

protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Priority>().MapSingleType().ToTable("tblPriority"); 
     modelBuilder.Entity<Priority>().HasKey(x => x.ID); 
     modelBuilder.Entity<Priority>().Property(x => x.CreatedDate).StoreGeneratedPattern = System.Data.Metadata.Edm.StoreGeneratedPattern.Computed; 
     modelBuilder.IncludeMetadataInDatabase = false; 
     base.OnModelCreating(modelBuilder); 
    } 
2

這裏是一個有用的鏈接解釋如何刪除並重新創建數據庫,如果模型的變化。 http://davidhayden.com/blog/dave/archive/2011/04/27/DatabaseInitializersEFCodeFirstDatabaseSetInitializer.aspx

下面是一個類似的,也許有幫助,問題和答案在這裏SO ... HTH How to manage GetDate() with Entity Framework

+0

我使用** Database.SetInitializer(new RecreateDatabaseIfModelChanges ()); **。 我得到這樣的錯誤。 System.NotSupportedException:對於不屬於'timestamp'或'rowversion'類型的屬性,不支持商店生成的模式'Computed'。 我無法手動更改默認值,EF也沒有設置默認值:( – whitestream

+0

@whitestream - 我用新鏈接更新了答案,希望它對你有幫助 – webtrifusion

+0

我使用的SQL Server 2005不支持' datetime2'類型我不明白爲什麼EF做到這一點,因爲我將'StoreGeneratedPattern'設置爲'Computed' – whitestream