【发布时间】:2014-02-14 00:25:51
【问题描述】:
我有一个具有 virtual Keywords 属性 (ICollection Keyword) 的 Product 模型类和具有 virtual Products 属性 (ICollection Product) 的 Keyword 模型类。
这个创建的表结构正是我要找的:3 个表,Product、Keyword 和 ProductKeyword(多对多关系表)。
在我的create 方法中,我试图在Product 表中创建一条记录,在Keyword 表中创建一条记录(如果给定的关键字尚不存在),然后在@ 中添加关系987654333@表。 Product 插入和 Keyword 插入一样有效,但我无法让 ProductKeyword 表插入工作。
代码如下:
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");
【问题讨论】:
标签: c# entity-framework