How to Get Tracked Entities
-
The Session tracks all changes made to all the entities it has either loaded, stored, deleted, or queried for,
and persists to the server only what is needed whenSaveChanges()is called. -
You can use the session's advanced
GetTrackedEntities()method
to retrieve the list of all entities tracked by the session. -
To check what is the actual type of change made to the entities, see:
Get entity changes, or Get session changes. -
In this page:
Get tracked entities
Tracking stored entities:
using (var session = store.OpenSession())
{
// Store entities within the session:
Employee employee1 = new Employee {FirstName = "John", LastName = "Doe"};
Employee employee2 = new Employee {FirstName = "David", LastName = "Brown"};
Employee employee3 = new Employee {FirstName = "Tom", LastName = "Miller"};
session.Store(employee1, "employees/1-A");
session.Store(employee2, "employees/2-A");
session.Store(employee3, "employees/3-A");
// Get tracked entities:
IDictionary<string, EntityInfo> trackedEntities = session.Advanced.GetTrackedEntities();
// The session tracks the 3 new stored entities:
Assert.Equal(3, trackedEntities.Keys.Count);
var entityInfo = trackedEntities["employees/1-A"];
Assert.Equal("employees/1-A", entityInfo.Id);
Assert.True(entityInfo.Entity is Employee);
// Save changes:
session.SaveChanges();
// The session keeps tracking the entities even after SaveChanges is called:
trackedEntities = session.Advanced.GetTrackedEntities();
Assert.Equal(3, trackedEntities.Keys.Count);
}
Tracking loaded and deleted entities:
using (var session = store.OpenSession())
{
// Load entity:
Employee employee1 = session.Load<Employee>("employees/1-A");
// Delete entity:
session.Delete("employees/3-A");
// Get tracked entities:
IDictionary<string, EntityInfo> trackedEntities = session.Advanced.GetTrackedEntities();
// The session tracks the 2 entities:
Assert.Equal(2, trackedEntities.Keys.Count);
// Note the 'IsDeleted' property that is set for deleted entities:
var entityInfo = trackedEntities["employees/3-A"];
Assert.True(entityInfo.IsDeleted);
// Save changes:
session.SaveChanges();
}
Tracking queried entities:
using (var session = store.OpenSession())
{
// Query for all employees:
var employees = session.Query<Employee>().ToList();
// Get tracked entities:
IDictionary<string, EntityInfo> trackedEntities = session.Advanced.GetTrackedEntities();
// The session tracks the entities loaded via the query:
Assert.Equal(2, trackedEntities.Keys.Count);
}
Syntax
IDictionary<string, EntityInfo> GetTrackedEntities();
public class EntityInfo
{
public string Id { get; set; }
public object Entity { get; set; }
public bool IsDeleted { get; set; }
}