实体框架代码第一播种数据

时间:2016-07-19 16:52:24

标签: c# entity-framework console-application

我首先使用代码实体框架中的方法,但我无法将默认数据播种到表中。请帮忙。

模型

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());
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

尝试实际查询数据库

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

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

答案 1 :(得分:0)

对于实体框架的第6版,使用&#39;迁移&#39;是使用&#34; Configuration.Seed&#34;对数据库进行版本控制的首选方法。本教程中显示的方法:

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

您是否尝试过运行&#34;更新数据库&#34;从包管理器控制台获得它的工作?

我知道我在使用EF6的旧播种方法时遇到了问题。实体框架核心1(以前称为EF7)的迁移也已更改,因此请确保将正确的技术应用于正确的版本。