whitestream
whitestream

Reputation: 691

EF - Code First - SQL Default Value getdate() gives error

I have a Priority class that has a datetime column. This column has a default value in SQL (after EF generates database and table , I changes default value of CreatedDate to getdate()). So I just want to insert into other columns of Priority but EF does not allow me and gives this error:

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);

    }

Upvotes: 1

Views: 5234

Answers (2)

whitestream
whitestream

Reputation: 691

in OnModelCreating method, I set modelBuilder.IncludeMetadataInDatabase to false and now everything is workink fine.

 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);
    }

Upvotes: 2

webtrifusion
webtrifusion

Reputation: 4556

Here is a helpful link to explain how to drop and recreate the database if the model changes. http://davidhayden.com/blog/dave/archive/2011/04/27/DatabaseInitializersEFCodeFirstDatabaseSetInitializer.aspx

Here is a similar, and maybe helpful, question and answer here on SO... HTH How to manage GetDate() with Entity Framework

Upvotes: 2

Related Questions