Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF DbContext.Set<T> filtered record only ... doesn't work

While developing a data access solution that utilizes generic repository and unit of work pattern over entity framework 4.2. I am seeing some abnormal behavior. To make my repositories generic, I have utilized the Set method of DbContext like:

public class MyGenericRepository<T> 
{
     protected readonly IDbContext context;
     public virtual IEnumerable<T> FindBy(Func<T, bool> predicate)
     {
        return context.GetDbSet<T>().Where(predicate).First();
     }
}

where IDbContext is like:

public interface IDbContext
{
    void Commit();
    void Attach<T>(T obj) where T : class;
    void Add<T>(T obj) where T : class;
    DbSet<T> GetDbSet<T>() where T : class;
    bool Remove<T>(T item) where T : class;
}

The DbContext class implements the IDbContext as:

public partial class MyEntities : IDbContext
{

    public DbSet<T> GetDbSet<T>() where T : class
    {
        return this.Set<T>();
    }
}  

When I do repository.FindBy(c => c.CompanyId == 45), Sql Profiler shows the query to NOT contain any filter (company_id = 45). The query does a Select *.

Expecting a filter to be present, i started researching and came across this,

http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/7d6705ac-f875-4c89-960b-842be6f6e5ed and EF DbContext.Set<T> filtered record only

These threads confirms my thought process but the results are different. Any solutions?

Thanks.

like image 786
Umair Ishaq Avatar asked Jan 19 '26 20:01

Umair Ishaq


1 Answers

Your predicate is a Func<T, bool>, which forces the query to use the Enumerable.Where method instead of the Queryable.Where method.

Change the predicate to Expression<Func<T, bool>> and everything should start working.

like image 130
Richard Deeming Avatar answered Jan 22 '26 08:01

Richard Deeming



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!