Question

I've been attempting to refactor some EF6 code to EF Core 1 and have hit a small stumbling block. The code I'm attempting to convert is here:

https://github.com/mehdime/DbContextScope

Everything is mostly fine but DbContextScope.cs in particular is proving tricky, e.g. this method (edited for brevity):

        public void RefreshEntitiesInParentScope(IEnumerable entities)
    {
        foreach (IObjectContextAdapter contextInCurrentScope in 
            _dbContexts.InitializedDbContexts.Values)
        {
            var correspondingParentContext =
                _parentScope._dbContexts.InitializedDbContexts.Values
                    .SingleOrDefault(parentContext => 
                        parentContext.GetType() == contextInCurrentScope.GetType())
                           as IObjectContextAdapter;

            if (correspondingParentContext == null)
                continue;

            foreach (var toRefresh in entities)
            {
                ObjectStateEntry stateInCurrentScope;
                if (contextInCurrentScope.ObjectContext.ObjectStateManager
                        .TryGetObjectStateEntry(toRefresh, out stateInCurrentScope))
                {
                    var key = stateInCurrentScope.EntityKey;

                    ObjectStateEntry stateInParentScope;
                    if (correspondingParentContext.ObjectContext.ObjectStateManager
                       .TryGetObjectStateEntry(key, out stateInParentScope))
                    {
                        if (stateInParentScope.State == EntityState.Unchanged)
                        {
                            correspondingParentContext.ObjectContext.Refresh(
                                RefreshMode.StoreWins, stateInParentScope.Entity);
                        }
                    }
                }
            }
        }
    }

Questions.

Firstly, I know I can replace ObjectContext.ObjectStateManager with the new ChangeTracker but want to ensure that the entry I obtain is obtained correctly.How would the following line translate in EF Core?

contextInCurrentScope.ObjectContext.ObjectStateManager
    .TryGetObjectStateEntry(toRefresh, out stateInCurrentScope)

Secondly, what is the equivalent of this in EF Core?

correspondingParentContext.ObjectContext.Refresh

Thanks!

P.s. There are many helpful comments in the source at the GitHub repo above.

1
2
7/18/2016 10:09:42 PM

Popular Answer

I think the correct way to get an entity's entry, and consequently it's keys and state, is via:

var entry = contextInCurrentScope.Entry(toRefresh);
var keys = entry.Metadata.GetKeys();
var state = entry.State;

you can also refresh a single entity from the database using the entry as follows:

entry.Reload();
1
12/12/2018 9:05:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow