简体   繁体   English

实体框架多对多插入

[英]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个表, ProductKeywordProductKeyword (多对多关系表)。

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.

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