问题描述:

I have set up an entity framework project with a code-first approach:

Link to code-first approach

I have added a method to access the repositories by inserting a function:

The interface for the repository:

IQueryable<T> GetMany(Func<T, bool> where);

The EntityRepositoryBase method:

public virtual IQueryable<T> GetMany(Func<T, bool> where)

{

return dbset.Where(where).AsQueryable();

}

Example of how I access it:

genericRepositoryName.GetStuffInHere(x => x.Name== "Billy");

However, when this is executed it is loading the entire table and filtering the data down. This, as you can imagine, takes a long time. I have a ByID approach that uses .Find() which correctly executes a query and gets the record in milliseconds flat. I am completely stumped as to why this happens - or what I am doing wrong. Is there a better approach to grabbing all records with a field, let's say, that contain a string of "Hello". It takes ~5-10 seconds with the current process to get records back.

网友答案:

at a guess...

with linq, to turn it into a sql query it must be given an expression tree which it can then translate into sql. I think your Func screws that up

try just dbset.Where(x -> x.Name=="Billy);

or as Kirk points out in the comments, change to an expression tree:

public virtual IQueryable<T> GetMany(Expression<Func<T, bool>> where)
网友答案:

If I had to guess, dbset isn't IQueryable<T> or a DbSet. It's probably some fashion of IEnumerable<T>, which is causing the entire table to be fetched and filtered in C# instead of SQL.

I'd make sure you're not changing the dbset into an enumerable anywhere by calling ToList() or putting it through a foreach loop.

相关阅读:
Top