簡體   English   中英

什么時候在Codefirst Entity Framework中創建數據庫?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM