Question

What would be the best way to obtain the list of entities loaded in a given EF 4.1 DbContext? I have been unsuccessful in attemps to locate a collection of DbEntityEntry.Entity objects loaded for a given context. It seems like it should be possible using a pattern similar to how DbContext.ChangeTracker.Entries() operates.

Was it helpful?

Solution

This will give you all entities in the context:

dbContext.ChangeTracker.Entries().Select(e => e.Entity)

but you will get them types as general Object.

OTHER TIPS

Here is a routine I use is Testing, so I can check values and state of all entries.

public static void ContextDumpTest(DbContext context) {

       Debug.WriteLine("====Begin Context Dump========");
       var dbsetList = context.ChangeTracker.Entries();
        foreach (var dbEntityEntry in dbsetList) {

            Debug.WriteLine(dbEntityEntry.Entity.GetType().Name + " => " + dbEntityEntry.State );
            switch (dbEntityEntry.State) {
                 case EntityState.Detached:
                 case EntityState.Unchanged:
                 case EntityState.Added:
                 case EntityState.Modified:
                    WriteCurrentValues(dbEntityEntry);
                     break;
                case EntityState.Deleted:
                     WriteSomeValues(dbEntityEntry);
                     break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
             Debug.WriteLine("==========End of Entity======");
        }
        Debug.WriteLine("==========End of Context======");
    }

    private static void WriteCurrentValues(DbEntityEntry dbEntityEntry) {
        foreach (var cv in dbEntityEntry.CurrentValues.PropertyNames) {
            Debug.WriteLine(cv + "=" + dbEntityEntry.CurrentValues[cv]);
        }
    }
    private static void WriteSomeValues(DbEntityEntry dbEntityEntry)
    {
        foreach (var cv in dbEntityEntry.OriginalValues.PropertyNames)
        {
            Debug.WriteLine(cv + "=" + dbEntityEntry.OriginalValues[cv]);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top