Adding An Additional Item To A Collection In Entity Framework With Repository Pattern

My application has Entities named ‘Hazards’ and ‘Hazard Groups’. A HazardGroup contains many Hazards and the Hazards may be moved from one HazardGroup to another via a Dialog Box.

I found when trying to add an existing Hazard to an existing HazardGroup that I was getting (to paraphrase) ‘Cannot create association: Objects were created in different Data Contexts’ error message. So I needed to put the Hazard and the HazardGroup in the same Object Context.

Here’s how I ended up doing it:

using (var ctx = new HazardContext())
{ {
Hazard movedHazard = _moved hazard returned from my Dialog Box_;
ctx.HazardGroups.Attach(SelectedHazardGroup);
ctx.Hazards.Attach(movedHazard);
SelectedHazardGroup.Hazards.Add(movedHazard);
}

Just to make it spicier I was also using the Repository Pattern, so I had to make sure that my SelectedHazardGroup was attached to the active Repository, like so:

using (var ctx = new HazardContext())
{
IRepository (Of HazardGroup) repo =
new Repository (Of HazardGroup)(ctx);

repo.Attach(SelectedHazardGroup);
Hazard movedHazard = _moved hazard returned from my Dialog Box_;
ctx.Substations.Attach(movedHazard);
SelectedHazardGroup.Hazards.Add(movedHazard);
repo.SaveChanges()
}

HTH.

Tags: , , ,

Leave a comment