我有2个表有多对多的关系,所以我创建了第3个表作为连接表,因为EF7不会自动创建它。
class Product
{
public int Id { get; set; }
public ICollection<Categorization> Categorizations { get; set; }
}
class Categorization
{
public int ProductId { get; set; }
public Product Product { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
class Category
{
public int Id { get; set; }
public ICollection<Categorization> Categorizations { get; set; }
}
因此,如果我想在产品中插入/播种新记录,我就这样做:
db.Products.AddRange(products); //where products = List<Product>
db.Categories.AddRange(categories);
db.SaveChanges();
db.Categories.ToList() //not using where class since tables are empty initially
.ForEach(c => db.Products.ToList()
.ForEach(p => db.Categorizations
.Add(new Categorization() { CategoryId = c.Id, ProductsId = p.Id })));
db.SaveChanges();
有没有有效而简单的方法来做同样的事情?谢谢。