简体   繁体   中英

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 ).

The table structure this created is what I was looking for: 3 tables, Product , Keyword , and ProductKeyword (many to many relationship table).

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. The Product insert works as well as the Keyword insert, but I cannot get the ProductKeyword table insert to work.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM