2)修改其代码如下:
public class AccountingInitializer :
System.Data.Entity.DropCreateDatabaseIfModelChanges<Accounting>
{
protected override void Seed(Accounting context)
{
Invoice invoice = new Invoice { Total = 20, InvoiceDate =
new DateTime(2011, 4, 14), Tax = 1.50 };
invoice.LineItems.Add(new LineItem
{ ItemCost = 2, ProductName = "Test", Units = 4 });
invoice.LineItems.Add(new LineItem
{ ItemCost = 4, ProductName = "Test 2", Units = 3 });
context.Invoices.Add(invoice);
context.SaveChanges();
base.Seed(context);
}
}
System.Data.Entity.DropCreateDatabaseIfModelChanges<Accounting>
{
protected override void Seed(Accounting context)
{
Invoice invoice = new Invoice { Total = 20, InvoiceDate =
new DateTime(2011, 4, 14), Tax = 1.50 };
invoice.LineItems.Add(new LineItem
{ ItemCost = 2, ProductName = "Test", Units = 4 });
invoice.LineItems.Add(new LineItem
{ ItemCost = 4, ProductName = "Test 2", Units = 3 });
context.Invoices.Add(invoice);
context.SaveChanges();
base.Seed(context);
}
}
其中,在这个类中继承了DropCreateDatabaseIfModelChanges这个类,并且重写了seed这个方法,在这个方法中可以编写新增测试数据。要记得还需要在Application_OnStart事件中编写如下代码:
void Application_Start(object sender, EventArgs e)
{
//在启动过程中执行该段代码
System.Data.Entity.Database.SetInitializer<Accounting>
(new AccountingInitializer());
}
{
//在启动过程中执行该段代码
System.Data.Entity.Database.SetInitializer<Accounting>
(new AccountingInitializer());
}
小 结
可以看到,Entity Framework 4.1的确方便了用户的开发操作,能让用户更专注于业务逻辑实体的开发,更符合OOP的思维方式,更多关于Entity Framework的操作,请参考微软的MSDN。