0

我一直在关注 Julie Lerman 关于使用 EF CodeFirst 从代码生成数据库的教程。我正在使用 MVC4 并使用默认控制器。我要做的就是生成数据库。然而,在她的教程中,她使用控制台应用程序并在她的 Main 函数中调用 create_blog 方法。顾名思义,create_blog 函数完成创建数据库的工作。

在我的 Global.asax 中,我有这个:

Database.SetInitializer(new CIT.Models.SampleData());

这是我的 SampleData 类:

 public class SampleData : CreateDatabaseIfNotExists<Context>
    {
        protected override void Seed(Context context)
        {
            base.Seed(context);


            new List<Software> {
                    new Software { Title = "Adobe Creative Suite", Version = "CS6", SerialNumber = "1234634543", Platform = "Mac", Notes = "Macs rock!", PurchaseDate = "2012-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Adobe" }}},
                    new Software { Title = "Apple iLife", Version = "2012", SerialNumber = "123463423453", Platform = "Mac", Notes = "Macs still rock!", PurchaseDate = "2012-11-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "81st Street" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Apple" }}},
                    new Software { Title = "Microsoft Office", Version = "2012", SerialNumber = "12346231434543", Platform = "PC", Notes = "Macs really rock!", PurchaseDate = "2011-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Microsoft" }}}
                }.ForEach(s => context.Software.Add(s));


        }
    }

编译时没有错误。我只是没有数据库。我查看了我的 App_Data,那里的所有内容都是默认数据库。我有一个被调用的 dbContext,因为当我在其中出现错误时,它们指向了该文件。我是否需要在网站首次编译时调用某种创建方法?

4

1 回答 1

0

SetInitializer 只设置初始化策略,策略在你第一次访问数据库时执行。调用 SetInitializer 后尝试添加以下内容

using (var context = new Context()) { context.Database.Initialize(true); }
于 2012-12-05T20:33:52.210 回答