无法初始化 MVC-5 ERF-6 中的表

Unable to Initialise tables in MVC-5 ERF-6

我的代码是这样的

    using System.Collections.Generic;
using System.Data.Entity;
using DiagnosisApp.Models;

namespace DiagnosisApp.DAL
{
    public class DiagnosisInitializer : DropCreateDatabaseIfModelChanges<DiagnosisContext>
    {
        protected override void Seed(DiagnosisContext context)
        {
            var departments = new List<Department>
            {
                new Department {Name = "aks", CreatedUser = "rahul", CreatedDate = "2005-09-01"},
                new Department {Name = "john", CreatedUser = "rahul", CreatedDate = "2005-09-01"},
                new Department {Name = "ninoo", CreatedUser = "aks", CreatedDate = "2005-09-01"},
            };
            departments.ForEach(s => context.Departments.Add(s));
            context.SaveChanges();
        }
    }
}

在我的控制器里面

   private DiagnosisContext db = new DiagnosisContext();
 public ActionResult Index()
    {
        return View(db.Departments.ToList());
    }

并在诊断上下文中

    using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using DiagnosisApp.Models;

namespace DiagnosisApp.DAL
{
    public class DiagnosisContext : DbContext
    {
        public DiagnosisContext() : base("DiagnosisContext")
        {
        }

        public DbSet<Department> Departments { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }


    }
}

并在网络配置中

      <connectionStrings>
    <add name="DiagnosisContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-DiagnosisApp-20150107051825.mdf;Initial Catalog=aspnet-DiagnosisApp-20150107051825;Integrated Security=True" providerName="System.Data.SqlClient" />
      </connectionStrings>



    <contexts>
    <context type="DiagnosisApp.DAL.DiagnosisContext, DiagnosisApp">
      <databaseInitializer type="DiagnosisApp.DAL.DiagnosisInitializer, DiagnosisApp" />
    </context>
  </contexts>

我觉得一切都很好。但是这个 class 并没有初始化或将这个虚拟数据添加到数据库中。谁能指出我在这里遗漏了什么?

注意:我是 MVC 的新手,所以按照本教程创建我的应用程序 http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

我认为您在 DiagnosisContext

的构造函数中错过了这行代码
public DiagnosisContext() : base("DiagnosisContext")
{
    Database.SetInitializer(new DiagnosisInitializer());
}

DropCreateDatabaseIfModelChanges 仅在您的数据库模型更改时触发 Seed 方法。因此,如果您在基于当前数据库模型创建数据库后将代码添加到种子方法,则种子方法将不会触发,直到您对模型进行更改(例如,将新字段添加到您的部门 class 将导致模型更改).

如果您希望始终触发 Seed 方法,则可以使用 DropCreateDatabaseAlways 策略代替 DropCreateDatabaseIfModelChanges。

另请注意,这两种策略仅在测试环境中有用,因为显然 drop/create 数据库会导致数据丢失