views:

22

answers:

1

Problem is it seems that when I use the code below to assign the location values obtained from a ListBox to the division being created/edited EF creates a new location and then enters that locations ID and the divisions is into the DivisionLocation table thus creating multiple locations unnecessarily, as depicted below.

using (FRLEntities context = new FRLEntities())
{
    for (int i = 0; i < lstPicked.Items.Count; i++)
    {
        var lpn = cm.GetLocation(Convert.ToInt32(lstPicked.Items[i].Value));
        Location cLocation = new Location { LocationId = Convert.ToInt32(lstPicked.Items[i].Value), LocationName = lstPicked.Items[i].Text, LocationParentName = lpn.LocationParentName };
        //CurrentDivision.Location = new EntityCollection<Location>();
        CurrentDivision.Location.Add(cLocation);
    }
}

Some data

Division
Divisionid           DevisionName
1                    1st Division
2                    2st Division

Location
LocationId           LocationName
1                    HG
2                    FG
3                    IK
4                    HG
5                    FG  

DivisionLocation
DivisionId           LocationId
1                    1
1                    3
2                    1
2                    2
2                    4
1                    5

Thanks in advance

A: 

It is common problem. You created Location instance in code and you didn't load it from EF context. So the Location intance is not related to current context and when you add new CurrentDivision to context all related Locations are also taken as new objects.

If you want to avoid this you have to somehow say EF context which locations are new and which are existing. I'm using this approach:

context.ObjectStateManager.ChangeObjectState(lpn, EntityState.Unchagned);
Ladislav Mrnka