种子方法如何使用foreach循环?

时间:2014-07-08 06:14:24

标签: c# asp.net-mvc entity-framework

 protected override void Seed(ContosoUniversity.DAL.SchoolContext context)
  {
      var students = new List<Student>
        {
            new Student { FirstMidName = "Carson",   LastName = "Alexander", 
                EnrollmentDate = DateTime.Parse("2010-09-01") },
            new Student { FirstMidName = "Meredith", LastName = "Alonso",    
                EnrollmentDate = DateTime.Parse("2012-09-01") },
            new Student { FirstMidName = "Arturo",   LastName = "Anand",     
                EnrollmentDate = DateTime.Parse("2013-09-01") },
            new Student { FirstMidName = "Gytis",    LastName = "Barzdukas", 
                EnrollmentDate = DateTime.Parse("2012-09-01") },
            new Student { FirstMidName = "Yan",      LastName = "Li",        
                EnrollmentDate = DateTime.Parse("2012-09-01") },
            new Student { FirstMidName = "Peggy",    LastName = "Justice",   
                EnrollmentDate = DateTime.Parse("2011-09-01") },
            new Student { FirstMidName = "Laura",    LastName = "Norman",    
                EnrollmentDate = DateTime.Parse("2013-09-01") },
            new Student { FirstMidName = "Nino",     LastName = "Olivetto",  
                EnrollmentDate = DateTime.Parse("2005-08-11") }
        };
     students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
     context.SaveChanges();

我在我的MVC项目中使用迁移,但在上面的代码中使用Configuration.cs文件。使用种子方法,但我不理解Foreach循环的语法。所以任何人都可以建议我。

1 个答案:

答案 0 :(得分:1)

List.ForEach方法就像'foreach'循环。它使用lambda对每个元素执行操作。

http://msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/bb397687.aspx