I have a database connected to a MVC 4 Project. The Database is creating automatically from this code:
public class ContextInitializer : DropCreateDatabaseIfModelChanges<ContextModel>
{
protected override void Seed(ContextModel context)
{
base.Seed(context);
}
}
I saw that people Seed back the database after drop and recreate with this code:
System.Data.Entity.Database.SetInitializer(new CarStore.Models.SampleData.cs);
This works grate. But my question is:
1st. How can I seed data from a SQL file, i have that SampleData.sql, and how can I 'run' that file to insert back all the data.
and 2nd is there a way to make BackUp to latest version from your database data, before you DropAndCreateIfModelChanges ? And then to seed that data back from that file ?
Thanks.
I GOT THE ANSWER :)
I finally manage to solve this problem.
Here is the code, maybe someone needs it !
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDirectory +
"\\IF YOU HAVE ANOTHER DIRECTOR INSIDE BASEDIR \\SQL" + "\\YOURFILENAME.sql"));
It works for me very good and fast. It's optimized and readable.