【问题标题】:Entity Framework Many to Many Insert实体框架多对多插入
【发布时间】:2014-02-14 00:25:51
【问题描述】:

我有一个具有 virtual Keywords 属性 (ICollection Keyword) 的 Product 模型类和具有 virtual Products 属性 (ICollection Product) 的 Keyword 模型类。

这个创建的表结构正是我要找的:3 个表,ProductKeywordProductKeyword(多对多关系表)。

在我的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


    【解决方案1】:

    使用Include 加载关系。

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

    【讨论】:

    • 成功了!谢谢。我需要做的唯一其他更改是还初始化 existingKeyword.Products = new List 如果它为空。
    猜你喜欢
    • 2011-06-02
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    相关资源
    最近更新 更多