我有一個優先級類,它有一個日期時間列。此列在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);
}
我使用** Database.SetInitializer(new RecreateDatabaseIfModelChanges()); **。 我得到這樣的錯誤。 System.NotSupportedException:對於不屬於'timestamp'或'rowversion'類型的屬性,不支持商店生成的模式'Computed'。 我無法手動更改默認值,EF也沒有設置默認值:( –
whitestream
@whitestream - 我用新鏈接更新了答案,希望它對你有幫助 – webtrifusion
我使用的SQL Server 2005不支持' datetime2'類型我不明白爲什麼EF做到這一點,因爲我將'StoreGeneratedPattern'設置爲'Computed' – whitestream