步骤4
在这个步骤中,我们学习如何改变数据模型。假设我们要在Invoice类中增加一个Tax的属性,也需要Entity框架同步在数据库中增加这个字段,下面演示其步骤:
1)我们在Invoice类中增加Tax这个属性。
2)如果这时运行工程,则会看到如下的错误提示:
The model backing the 'Accounting' context has changed since the database was
created. Either manually delete/update the database, or call
Database.SetInitializer with an IDatabaseInitializer instance. For example, the
DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate
the database, and optionally seed it with new data.
created. Either manually delete/update the database, or call
Database.SetInitializer with an IDatabaseInitializer instance. For example, the
DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate
the database, and optionally seed it with new data.
提示告诉我们,或者这个时候重新手工删除数据库或者使用代码的方法去完成,我们使用代码的方法去完成,只需要在Application_Start事件中编码如下,即可让Entity框架,自动把新增加的属性反映到数据库中:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
System.Data.Entity.Database.SetInitializer<Accounting>
(new System.Data.Entity.DropCreateDatabaseIfModelChanges<Accounting>());
}
{
// Code that runs on application startup
System.Data.Entity.Database.SetInitializer<Accounting>
(new System.Data.Entity.DropCreateDatabaseIfModelChanges<Accounting>());
}
3) 再次运行工程,会看到数据表中的确增加了Tax这个字段了,如下图:
步骤5
注意,在上面的步骤4中,如果类的属性发生变化,则其实是通过代码的方法,重新将旧的数据库DROP掉,然后再新建,这样的话费时费力,而可以通过另外的一个方法实现,即还好我们可以在初始化的过程中添加测试数据,这样每次重新创建数据库的时候,测试数据就会自动加进去了,算是解决了一些问题,方法如下:
1)在工程项目中,新增加一个类,命名为AccountingInitializer.cs