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

送分小仙女□ 提交于 2019-12-30 01:12:30

问题


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

When I generated the Database it creates many-to-many between Movie and type

So, What should i do to seed this many to many table? I tried many solution posted here but it didn't works.

Also, is this the best way to Generate a Many-To-Many Relation using EF code first


回答1:


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


来源:https://stackoverflow.com/questions/14183163/how-should-i-seed-data-to-many-to-many-relation-in-entity-framework-code-first-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!