0

Sorry if my question is a bit stupid, but I got really stuck with this basic thing. I have generic repository that has method like this:

protected List<T> GetEntities(Expression<Func<T, bool>> whereExpression)
    {
        var query = Context.Set<T>().AsQueryable();

        if (whereExpression != null)
            query = query.Where(whereExpression).AsQueryable();

        List<T> result = query.ToList();

        return result;
    }

Our app should allow to work with data without commiting to database. But at any time user should be able to save changes. For adding or deleting entries I use:

 Context.Set<T>().Add(entity);

and

 Context.Set<T>().Remove(entity);

But after I call GetEntities deleted entities appear again and new entities does not appear. Obviosuly that GetEntities queries directly database and does not take in account local changes.

So, my question: is there any easy way to combine where-expression on data loaded from database and local changes?

Thanks.

Renat Khabibulin
  • 183
  • 2
  • 11
  • It's a little unclear what you want. When exactly do you want to access a local in memory representation of the data, and when do you want to access the database? – Nick Bailey Jun 03 '16 at 12:47
  • I think that you should use the same DbContext instance while the user is editing the data. – dvjanm Jun 03 '16 at 13:16
  • 1
    Yes the query goes against the datasource, this will help you to solve the problem :http://stackoverflow.com/questions/699648/entity-framework-re-finding-objects-recently-added-to-context – Bassam Alugili Jun 03 '16 at 13:22
  • How do you get your instance of the repository? I think that you inject the DbContext by constructor. Well you should manage to create all of your repository instances with the same instance of DbContext. Do you use an IOC also? – dvjanm Jun 03 '16 at 13:30
  • Comment added by Bassam looks correct....unfortunatelly....Looks like I have to add more code that will handle my local changes. I will do more investigation on this and post an update here – Renat Khabibulin Jun 03 '16 at 18:02

1 Answers1

1

I sometimes use this little method to give preference to local data:

public static IQueryable<TEntity> PreferLocal<TEntity>(this DbSet<TEntity> dbSet, 
    Expression<Func<TEntity, bool>> predicate)
        where TEntity : class
{
    if (dbSet.Local.AsQueryable().Any(predicate))
    {
        return dbSet.Local.AsQueryable().Where(predicate);
    }
    return dbSet.Where(predicate);
}

It first tries to find entities in the Local collection (and because its all in-memory, the extra Any isn't expensive). If they're not there, the database is queried.

In your repository you could use like so:

return PreferLocal(Context.Set<T>(), whereExpression).ToList();

But maybe you also should re-consider the life cycle of your Context. It looks like you have a long-lived context, which isn't recommended.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291