【问题标题】:Entity framework fundamentals实体框架基础
【发布时间】:2023-11-01 15:41:01
【问题描述】:

我在 ASP.NET MVC4 应用程序中使用 EF5 codefirst。我有产品和合作伙伴,可以为一个产品分配多个合作伙伴。

在 Product 实体中,我有这个: 公共 ICollection 合作伙伴 { 获取;放; }

在合作伙伴实体中,我有这个: 公共 ICollection 产品 { 获取;放; }

因此在我的 sql server 中,PartnerProducts many-2-many 表是由代码首先创建的。

然后我就有了这个动作方法:

    public ActionResult AssignPartner(long productId,  long partnerId) {
        var product = productRepository.Find(productId);
        var partner = partnerRepository.Find(partnerId);
        if (product.Partners == null) {
            product.Partners = new List<Partner>();
        }
        product.Partners.Add(partner);
        productRepository.Save();
        return RedirectToAction("Edit", new{ Id = productId });
    }

但结果是创建了一个新的 PartnerProducts 行(好的),并且在 Partners 表中创建了一个新的合作伙伴?不知何故,EF 一定认为我添加的伙伴是新记录?

我在这里错过了什么?

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    试试这个:

    public ActionResult AssignPartner(long productId,  long partnerId)
    {
        var product = productRepository.Find(productId);
        var partner = partnerRepository.Find(partnerId);
    
        // Using Attach - partner will be in state Unchanged in the context
        dbContext.Partners.Attach(partner);
    
        if (product.Partners == null)
        {
            product.Partners = new List<Partner>();
        }
    
        product.Partners.Add(partner);
    
        productRepository.Save();
    
        return RedirectToAction("Edit", new{ Id = productId });
    }
    

    【讨论】: