【问题标题】:When is the time a database is created in Codefirst Entity Framework?在 Code First Entity Framework 中创建数据库的时间是什么时候?
【发布时间】:2013-01-26 00:39:35
【问题描述】:

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

【问题讨论】:

  • 如果要按需创建数据库,可以运行 NU-GET 控制台命令 UPDATE-DATABASE -Verbose...
  • 会不会也创建里面的所有表?
  • 是的,它将创建从模型中看到的所有内容

标签: c# entity-framework


【解决方案1】:

您可以管理该过程。但默认情况下,每次应用程序启动期间数据模型发生变化时,db 都会重新创建。

如果您对该过程感兴趣,请阅读this article

【讨论】:

  • 我的问题是当数据尚未插入任何表时,它无法创建数据库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-30
相关资源
最近更新 更多