我应该如何在Entity Framework Code first 5.0中将数据播种到多对多关系 [英] How should I seed data to many to many relation in Entity Framework Code first 5.0
问题描述
我在EF 5.0中迈出了第一步,
我有很多对很多的关系。电影可以具有多种类型,类型可以具有多种电影
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.
此外,这是首先使用EF代码生成多对多关系的最佳方法
Also, is this the best way to Generate a Many-To-Many Relation using EF code first
推荐答案
只需创建一些电影和几种类型,并通过将其中一些类型添加到 Movie中来创建关系即可。类型
的集合(或相反),例如:
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);
}
这篇关于我应该如何在Entity Framework Code first 5.0中将数据播种到多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!