EF代码优先:集合已被修改

本文关键字:修改 集合 代码 EF | 更新日期: 2023-09-27 18:29:12

尝试将项目添加到我的存储库/上下文时出现此错误:

集合已被修改。可能未执行库存操作。

我想做什么

Campaign c = Campaignrepository.FindById(id);
if (c.LandingPage == null)
{
    c.LandingPage = new Page() { Campaign = c, CampaignID = c.Campaignid };
    PageRepository.Add(c.LandingPage);
}
if (c.RedeemPage == null)
{
    c.RedeemPage = new RedeemPage() { Campaign = c, CampaignID = c.Campaignid };
    PageRepository.Add(c.RedeemPage);
}

Repository Add方法:

public void Add(Page p)
{
    pages.Add(p);
    context.SaveChanges();
}

更新:仍然存在相同的错误。

应用建议后:

public ActionResult Edit(int id)
{
    Campaign c = Campaignrepository.FindById(id);
    Campaign newreferenceC = Campaignrepository.FindById(id);
    if (c.LandingPage == null)
    {
        c.LandingPage = new Page() { Campaign = newreferenceC, CampaignID = newreferenceC.Campaignid };
        PageRepository.Add(c.LandingPage);
    }
    if (c.RedeemPage == null)
    {
        c.RedeemPage = new RedeemPage() { Campaign = newreferenceC, CampaignID = newreferenceC.Campaignid };
        PageRepository.Add(c.RedeemPage);
    }
    return View("Edit", Campaignrepository.FindById(id));
}

EF代码优先:集合已被修改

设法用修复它

        Page landingPage = new Page(c);
        RedeemPage redeemPage = new RedeemPage(c);
        PageRepository.Add(landingPage);
        PageRepository.Add(redeemPage);
        c.LandingPage = landingPage;
        c.RedeemPage = redeemPage;
        Campaignrepository.Update(c);