我刚接触Entity Framework,我目前正在Codefirst上练习生成我的模型。我遇到的一个困惑是,当我调用DbContext来创建整个模式时,我需要先将数据插入到任何表中,然后再创建所有表。这有意义吗?或许我刚刚对我的代码做错了。感谢?
以下是示例代码:
模型
public class Employee
{
public int EmployeeID { get; set; }
public string Firstname { get; set; }
public string Middlename { get; set; }
public string Lastname { get; set; }
}
这是我的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; }
}
加载数据库......
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();
}
}