2

私はEntityFrameworkを初めて使用し、現在、モデルを生成するためにCodefirstで練習しています。私が抱えている混乱の1つは、スキーマ全体を作成するために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();
    }
}
4

1 に答える 1

1

あなたはそのプロセスを管理することができます。ただし、デフォルトでは、アプリケーションの起動中にデータモデルが変更されるたびにdbが再作成されます。

そのプロセスに深く興味がある場合は、この記事を読んでください

于 2013-01-26T00:50:22.887 に答える