Entity Framework Code First 播种数据

Entity Framework Code First Seeding Data

我在 entity framework 中使用代码优先方法,但我无法将默认数据播种到 table 中。请帮忙。

型号

public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }


        public virtual Department Departments { get; set; }

    }
 public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public virtual ICollection<Employee> Employees { get; set; }

        public Department()
        {
            this.Employees = new List<Employee>();
        }

    }

初始化程序

public class DepartmentInitializer : DropCreateDatabaseIfModelChanges<EmployeeDBContext>
    {
        protected override void Seed(EmployeeDBContext context)
        {
            IList<Department> lst = new List<Department>
            {
                new Department
                {
                    Name = "Developer",
                    Location = "Bangalore"
                },
                new Department
                {
                    Name = "Tester",
                    Location = "Bangalore"
                },
                new Department
                {
                    Name = "IT Services",
                    Location = "Chennai"
                }
            };
            foreach (var item in lst)
            {
                context.Departments.Add(item);
            }
            context.SaveChanges();
        }
    }

主应用程序

class Program
    {
        static void Main(string[] args)
        {
            using (var db = new EmployeeDBContext())
            {
                Database.SetInitializer<EmployeeDBContext>(new DepartmentInitializer());
            }
        }
    }

尝试实际查询您的数据库

在我的机器上,播种器在我第一次查询时运行。

using (var db = new EmployeeDBContext())
{
    Database.SetInitializer<EmployeeDBContext>(new DepartmentInitializer());
    var depts = db.Departments.ToList();
}

对于 Entity Framework 的版本 6,使用 'migrations' 是对数据库进行版本控制的首选方法,使用本教程中所示的 "Configuration.Seed" 方法:

http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-3

您是否尝试过 运行 "Update-Database" 从程序包管理器控制台让它工作?

我知道我在使用旧的 EF6 播种方法时遇到了问题。 Entity Framework Core 1(以前称为 EF7)的迁移也发生了变化,因此请确保您将正确的技术应用于正确的版本。