When my code reaches CampaignRepository.saveChanges() it gives and error that the relation can not be modified, key properties can not be null. But if I debug it and look into the contents of the current object all primary keys and foreign keys are set. I have no clue why it's going wrong...
public ActionResult Update(LandingPage update)
{
Campaign curr = CampaignRepository.FindById(update.CampaignId);
curr.UpdatePage(update);
CampaignRepository.SaveChanges();
return View("Edit", curr);
}
public void UpdatePage(LandingPage update)
{
foreach (Page page in Pages)
{
if (page.Id == update.Id)
{
Pages.Remove(page);
break;
}
}
Pages.Add(update);
}
de relatie kan niet worden gewijzigd, omdat voor een of meer van de referentiële-sleuteleigenschappen geen null-waarde is toegestaan. Wanneer een relatie wordt gewijzigd, wordt de gerelateerde referentiële-sleuteleigenschap ingesteld op een null-waarde. Als de referentiële sleutel null-waarden niet ondersteunt, moet er een nieuwe relatie worden gedefinieerd, moet de referentiële-sleuteleigenschap worden toegewezen aan een andere waarde die niet null is of moeten het niet-gerelateerde object worden verwijderd.
Update
I changed my Update method to:
public ActionResult Update(LandingPage update)
{
Campaign curr = Campaignrepository.FindById(update.CampaignId);
PageRepository.Remove(update);
curr.Pages.Remove(update);
curr.Pages.Add(update);
Campaignrepository.SaveChanges();
return View("Edit", curr);
}
But now it says "The Object can not be removed because it's not found in the ObjectManager".
Update 2
Still "The Object can not be removed because it's not found in the ObjectManager".
//A campaign has Pages property which is a collection of Pages
//This collection contains a two (no more, no less) objects a LandingPage and a RedeemPage
//both LandingPage and RedeemPage have as base Page
//The objective is to replace the old LandingPage with the new version
public ActionResult Update(LandingPage update)
{
//Get the campaign it's about
Campaign curr = Campaignrepository.FindById(update.CampaignId);
//Set the current Page his foreign key values to null
curr.GetLanding().Campaign = null;
curr.GetLanding().CampaignId = 0;
//Remove the (current) page from the repository/context
PageRepository.Remove(update);
//Remove the (current) page from the Campaign collection
curr.Pages.Remove(update);
//Add the new version of the page
curr.Pages.Add(update);
//Save the chances => ObjectManager error
PageRepository.SaveChanges();
return View("Edit", curr);
}