2014-02-13 186 views
0

我有一個具有virtual Keywords屬性(ICollection Keyword),並具有virtual Products屬性(ICollection Product)一Keyword模型類Product模型類。實體框架多對多插入

創建的表結構是我正在尋找的:3個表,Product,KeywordProductKeyword(多對多關係表)。

在我create方法,我想創建的Product表中的記錄,在Keyword表中的記錄(如果給定的關鍵字不存在),然後在ProductKeyword表中添加的關係。該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"); 

回答

0

使用Include加載的關係。

db.Keywords.Include("Products").FirstOrDefault(k => k.Content == keyword) 
+1

這工作!謝謝。我需要做的唯一其他的變化是還初始化existingKeyword.Products =新名單如果它是空的。 – Jon