EF代码首先:如何以一对多关系种植表格? [英] EF Code First: how to seed tables in a One-To-Many relationship?
本文介绍了EF代码首先:如何以一对多关系种植表格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的模型
public class Movie
{
public int MovieID { get; set; }
public int GenreID { get; set; }
[Required, StringLength(200)]
public string Title { get; set; }
public int MovieLength { get; set; }
[Required, StringLength(1000)]
public string MovieSummary { get; set; }
public virtual Genre Genre { get; set; }
}
public class Genre
{
public int GenreID { get; set; }
public string GenreName { get; set; }
public virtual IEnumerable<Movie> Movies { get; set; }
}
public class ZimelleShopDbContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
public DbSet<Genre> Genres { get; set; }
}
ScottGu已经写了一个教程,显示如何种子表。我想知道如何种上上面的例子,以便在一对多关系中使用这两个表。
ScottGu has written a Tutorial that shows how to seed a table. I'd like to know how to seed the above example with in case of those 2 tables in One-To-Many relationship.
感谢您的帮助
编辑
我做到了另一回事,它的工作。我唯一需要照顾的是实例化ICollection。
I did it the other way around, and it worked. The only thing I had to take care of is to instantiate the ICollection.
public class Genre
{
public Genre()
{
Movies = new List<Movie>();
}
//...
}
然后我做了这个
protected override void Seed(ZimelleShopDbContext context)
{
var genre = new Genre { GenreName = "Foo" };
var movie = new Movie { Title = "Bar", MovieSummary = "Baz" };
genre.Movies.Add(movie);
context.Genres.Add(genre);
context.SaveChanges();
}
它仍然有效。
推荐答案
您需要替换 IEnumerable< Movie>电影
与 ICollection< Movie>电影
因为 IEnumerable
不是收集界面。
You need to replace IEnumerable<Movie> Movies
with ICollection<Movie> Movies
because IEnumerable
is not a collection interface.
public class Genre
{
public int GenreID { get; set; }
public string GenreName { get; set; }
public virtual ICollection<Movie> Movies { get; set; }
}
在您的初始化程序中
protected override void Seed(ZimelleShopDbContext context)
{
var genre = new Genre { GenreName = "Foo" };
var movie = new Movies { Title = "Bar", MovieSummary = "Baz", Genre = genre };
context.Movies.Add(movie);
context.SaveChanges ();
}
这篇关于EF代码首先:如何以一对多关系种植表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文