私は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();
}
}