How should I seed data to many to many relation in Entity Framework Code first 5.0

前端 未结 2 918
说谎
说谎 2021-02-04 07:20

I am having my first steps in EF 5.0 I have a many to many relationship. Movie can Have multiple Types and Type can have multiple Movies

public class Movie
{
            


        
相关标签:
2条回答
  • 2021-02-04 07:43

    You need a joining table to implement a many-to-many relationship.

    For example, think of a scenario where students can enroll in multiple courses and a course can have mutiple students.

    Class structure would look like,

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

    To seed data, just create instances of the CourseStudent class and AddOrUpdate on the DbSet.

        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 });
    
    0 讨论(0)
  • 2021-02-04 07:55

    Just create a few movies and a few types and create relationships by adding some of those types to the Movie.Types collection (or the other way around), for example:

    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);
    }
    
    0 讨论(0)
提交回复
热议问题