我只是 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();
}
}