[英]When is the time a database is created in Codefirst Entity Framework?
我是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();
}
}
您可以管理该过程。 但是默认情况下,每次在应用程序启动期间更改数据模型时,db都会重新创建。
如果您对此过程有浓厚的兴趣,请阅读本文
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.