I’m just new to Entity Framework and I currently practicing on Codefirst to generate my models. One confusion I have was that, when I’m calling the DbContext to create the whole schema it would need me to insert data first to any of the tables before all of them will be created. Does this make sense? Or maybe I’ve just done something wrong with my codes. Thanks?
Here’s a sample code:
Model
public class Employee
{
public int EmployeeID { get; set; }
public string Firstname { get; set; }
public string Middlename { get; set; }
public string Lastname { get; set; }
}
Here’s my DBContext:
public class MyContext : DBContext
{
public MyContext():base(@"
Data Source=(localdb)\v11.0;
AttachDbFilename=c:\users\nsutgio\MyDB.mdb;
Initial Catalog=MyDB;
Integrated Security=true;
Connection Timeout=30")
{
}
// I override onModelCreating here...
public DbSet<Employee> Employee { get; set; }
}
Load the database…
private void loadDB()
{
using(MyDBContext ctx = new MyDBContext())
{
// The commented code here is the one I've said, If I'll comment out this code below
// the database will not be created. My question is do we really need to insert data
//first before the whole database will be created?
//Employee _ee = new Employee();
//_ee.Firstname = "nsutgio";
//ctx.Employee.Add(_ee);
ctx.SaveChanges();
}
}
You could manage that process. But by default db recreates each time when data model changing during application start.
If you interested deeply in that process read this article