[英]Entity Framework Many to Many Insert
I have a Product
model class that has a virtual Keywords
property ( ICollection Keyword
) and a Keyword
model class that has a virtual Products
property ( ICollection Product
). 我有一个具有virtual Keywords
属性( ICollection Keyword
)的Product
模型类和具有virtual Products
属性( ICollection Product
)的Keyword
模型类。
The table structure this created is what I was looking for: 3 tables, Product
, Keyword
, and ProductKeyword
(many to many relationship table). 创建的表结构正是我要寻找的:3个表, Product
, Keyword
和ProductKeyword
(多对多关系表)。
In my create
method I am trying to create a record in the Product
table, a record in the Keyword
table (if the given keyword doesn't already exist) and then add the relationships in the ProductKeyword
table. 在我的create
方法中,我试图在Product
表中创建一条记录,在Keyword
表中创建一条记录(如果给定的关键字尚不存在),然后在ProductKeyword
表中添加关系。 The Product
insert works as well as the Keyword
insert, but I cannot get the ProductKeyword
table insert to work. Product
插入与Keyword
插入一样好,但是我无法使ProductKeyword
表插入起作用。
Here's the code: 这是代码:
if (!ModelState.IsValid)
{
return View(product);
}
product.AddedDate = DateTime.Now;
foreach (string keyword in splitter.Split().Distinct())
{
var existingKeyword = db.Keywords.FirstOrDefault(k => k.Content == keyword);
if (existingKeyword == null)
{
existingKeyword = db.Keywords.Add(new Keyword() { Content = keyword });
}
//product.Keywords.Add(existingKeyword) or existingKeyword.Products.Add(product) both fail here with a null reference exception
}
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
使用Include
来加载关系。
db.Keywords.Include("Products").FirstOrDefault(k => k.Content == keyword)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.