Fork me on GitHub

Ejecting Documents from a Session Edit on GitHub


If for some reason you need to completely remove a document from a session's identity map and unit of work tracking, as of Marten 2.4.0 you can use the IDocumentSession.Eject<T>(T document) syntax shown below in one of the tests:


[Fact]
public void demonstrate_eject()
{
    var target1 = Target.Random();
    var target2 = Target.Random();

    using (var session = theStore.OpenSession())
    {
        session.Store(target1, target2);

        // Both documents are in the identity map
        session.Load<Target>(target1.Id).ShouldBeTheSameAs(target1);
        session.Load<Target>(target2.Id).ShouldBeTheSameAs(target2);

        // Eject the 2nd document
        session.Eject(target2);

        // Now that 2nd document is no longer in the identity map
        session.Load<Target>(target2.Id).ShouldBeNull();
        
        session.SaveChanges();
    }

    using (var session = theStore.QuerySession())
    {
        // The 2nd document was ejected before the session
        // was saved, so it was never persisted
        session.Load<Target>(target2.Id).ShouldBeNull();
    }
}