我应该如何在实体框架代码5.0中将数据种子化为多对多关系

时间:2013-01-06 14:41:22

标签: entity-framework ef-code-first entity-framework-5

我在EF 5.0中迈出了第一步 我有很多关系。电影可以有多种类型和类型可以有多个电影

public class Movie
{
    public int MovieId { get; set; }
    [Required]
    public string Name { get; set; }

    public virtual ICollection<Type> Types { get; set; }
}


public class Type
{
    public int TypeId { get; set; }
    public string MovieType { get; set; }

    public virtual ICollection<Movie> Movies { get; set; }
}

当我生成数据库时,它会在Movie和type

之间创建多对多

那么,我应该怎样做才能将这个多表种子播种?我在这里尝试了很多解决方案,但它没有用。

此外,这是使用EF代码首先生成多对多关系的最佳方式

2 个答案:

答案 0 :(得分:28)

只需创建一些电影和几种类型,然后通过将一些类型添加到Movie.Types集合(或其他方式)来创建关系,例如:

protected override void Seed(MyContext context)
{
    var movie1 = new Movie { Name = "A", Types = new List<Type>() };
    var movie2 = new Movie { Name = "B", Types = new List<Type>() };
    var movie3 = new Movie { Name = "C", Types = new List<Type>() };

    var type1 = new Type { MovieType = "X" };
    var type2 = new Type { MovieType = "Y" };

    movie1.Types.Add(type1);

    movie2.Types.Add(type1);
    movie2.Types.Add(type2);

    movie3.Types.Add(type2);

    context.Movies.Add(movie1);
    context.Movies.Add(movie2);
    context.Movies.Add(movie3);
}

答案 1 :(得分:0)

您需要一个联接表来实现多对多关系。

例如,考虑一种情况,即学生可以注册多个课程,而一门课程可以有多个学生。

类结构看起来像

class Course
{  
  public int Id { get; set; }
  public string Name { get; set; }

}

class Student
{  
  public int Id { get; set; }
  public string Name { get; set; }

}

class CourseStudent
{  
  public int Id { get; set; }
  public int CourseId { get; set; }
  public int StudentId { get; set; }
  public Course Course { get; set; }
  public Student Student { get; set; }
}

要播种数据,只需创建 CourseStudent 类的实例并在DbSet上创建AddOrUpdate。

    var course1 = new Course { Name = "course1" };
    var course2 = new Course { Name = "course2" };

    var student1 = new Student { Name = "student1" };
    var student2 = new Student { Name = "student2" };

context.CourseStudents.AddOrUpdate(r => r.Id,
                new CourseStudent { Course = course1, Student = student1 },
                new CourseStudent { Course = course1, Student = student2 },
                new CourseStudent { Course = course2, Student = student1 },
                new CourseStudent { Course = course2, Student = student2 });