I am new to the Entity Framework and have the following problem:
I get a list of objects from the ObjectContext (RepEntities) which is used to populate a grid. The grid allows users to modify and select the binded objects. Once this is done I add the selected objects to another parent object. The issue is that when a property is changed for a specific object it also changes the property in other parent objects which have the same selected child object. Therefore, the ObjectSet returns a reference to the same objects each time.
I solved my issue by manually cloning the objects in the ObjectSet as follows:
public List<mblDataItem> GetSupportDataItems()
{
var items= (from e in RepEntities.jblDatItemDatTypes
where e.mblDataType.dtDsc == "Support"
select e.mblDataItem).OrderBy(p => p.diDsc).ToList();
mblDataItem di;
List<mblDataItem> diItems = new List<mblDataItem>();
foreach (var item in items)
{
di = new mblDataItem();
di.diID = item.diID;
di.diDsc = item.diDsc;
di.diSQL = item.diSQL;
di.Influence = item.Influence;
di.Comment = item.Comment;
di.PrimValue = item.PrimValue;
di.CompValue = item.CompValue;
diItems.Add(di);
}
return diItems;
}
What is the proper way of cloning/duplicating the ObjectSet ? Also, the way I am doing it I will not be able to use the navigation properties to get related entities.
UPDATE:
Ok, so I tried doing it as explained on Cloning an Entity in Linq-to-Entities and suggested by Schwarzie2478.
This does not work for me as I need to clone more than one object. What I need is to have a multiple collections of mblDataItems whose properties can be set independently from each other but still have the same EntityKey, so that inserts are done correctly. I also noticed that my first solution is flawed, because when I call SaveChanges() it inserts additional mblDataItems and then uses the newly inserted IDs in my joining table, instead of the existing mblDataItem IDs. What am I doing wrong?