Query Entity Framework, including records that were not committed

Is it possible to query the context, make changes to the object, and then re-query the context and get a result set that includes the modified object without making changes? (I do not want to save the changes because I can roll back)

I know that I can revert changes using GetObjectStateEntries, but I'm interested in the whole data set .. not just the changed objects.

I think the only way to do this is with savechanges, but wrap the transaction around everything so that I can roll back if my condition is not met. Or am I missing something simpler?

+5
source share
1 answer

? , , , - Deletes, :

// get the entities that have been inserted or modified
var projects = myObjectContext.ObjectStateManager.GetObjectStateEntries(
     EntityState.Added | EntityState.Modified).Where(
          x => x.Entity is Project).Select( x=> (Project) x.Entity);

// get existing entities, exclude those that are being modified
var projects2 = myObjectContext.Projects.Where(
     BuildDoesntContainExpression<Project, int>(z => z.ProjectId, 
          projects.Select(x => x.ProjectId)));

// Union the 2 sets
var projects3 = projects.Union(projects2);

BuildDoesntContainExpression: contains, - EF, :

    private static Expression<Func<TElement, bool>> BuildDoesntContainExpression<TElement, TValue>(    
        Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
    {    
        if (null == valueSelector) 
        { 
            throw new ArgumentNullException("valueSelector"); 
        }

        if (null == values) 
        { 
            throw new ArgumentNullException("values"); 
        }    

        ParameterExpression p = valueSelector.Parameters.Single();    

        // p => valueSelector(p) == values[0] || valueSelector(p) == ... 
        if (!values.Any())    
        {        
            return e => false;    
        }    

        var equals = values.Select(
            value => (Expression)Expression.NotEqual(valueSelector.Body, Expression.Constant(value, typeof(TValue))));    

        var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.And(accumulate, equal));    

        return Expression.Lambda<Func<TElement, bool>>(body, p);
     }
+3

All Articles