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.
Asked
Active
Viewed 4,386 times
1

Jakkwylde
- 1,304
- 9
- 16
2 Answers
3
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
.

Ladislav Mrnka
- 360,892
- 59
- 660
- 670
2
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]);
}
}

phil soady
- 11,043
- 5
- 50
- 95