Search code examples
c#.netframeworksentity

Entity framework 1.0 issue


When using 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 division is put into the DivisionLocation table thus creating unecessary additional locations 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);
    }
}

Here is the data that is has to work with.

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


Solution

  • 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);