为什么我的数据库不是使用EF CodeFirst在ASP.NET MVC4中创建的

时间:2012-12-05 20:28:01

标签: asp.net-mvc entity-framework

我一直在关注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,因为当我遇到错误时,他们指向该文件。我需要在网站首次编译时调用某种创建方法吗?

1 个答案:

答案 0 :(得分:0)

SetInitializer仅设置初始化策略,并在您第一次访问数据库时执行策略。尝试在调用SetInitializer

后添加以下内容
using (var context = new Context()) { context.Database.Initialize(true); }