I have a LINQ Query that returns a single object - the context is an ObjectContext not a DbContext
var q = from c in context.x //this has various includes but this just an example
where c.Id == xId
select c;
X x = q.FirstOrDefault();
I am then attaching a collection to this by using the following
ObjectQuery<Z> y = x.Y.CreateSourceQuery().Include("1").Include("2");
x.Y.Attach(y);
However there is a problem where I attempt to refresh the loaded object and if any items attached in the source query were removed they do not change on refresh.I believe this is because the context only loads each object once and keeps it cached, however I need to keep the context open as I need to save back to the database.
I have attempted to refresh using the following:
context.Refresh(RefreshMode.StoreWins, y);
or triggering a triggering a refresh by setting the entity state to modified:
context.ObjectStateManager.ChangeObjectState(pb, EntityState.Modified);
I understand that with a DB context you can refresh the entity forcing a database refresh, my question would be is it possible to force the refresh using ObjectContext.
Using DbContext we were able to get the desired results by refreshing everything however as you can imagine this was very slow.
var refreshableObjects = context.ChangeTracker.Entries().Select(e => e.Entity).ToList();
foreach (var obj in refreshableObjects)
{
((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetRelationshipManager(obj).GetAllRelatedEnds().Where(r => r.IsLoaded).ToList().ForEach(c => c.Load());
}