0

I've created a brand new Project in .NET Core 3.1 and a query I am creating is generating a SQL query (viewed in SQL Server Profiler) that does not contain a where clause and instead reads in the entire table. Is there a way to pass in a predicate and have that incorporated into the SQL statement that is ultimately generated?

In the below function query1 is an IQueryable<Balance> and query2 is an IEnumerable<Balance>:

    public int GetCount(Func<Balance, bool> predicate)
    {
        var query1 = (from b in _appContext.Balance
                      select b
                      );
        var query2 = query1.Where(predicate);
        var count = query2.Count();

        return count;
    }

Called like this:

    GetCount(p => p.Email == 'test@gmail.com');
Brian Rice
  • 3,107
  • 1
  • 35
  • 53
  • Does this answer your question? [converting a .net Func to a .net Expression>](https://stackoverflow.com/questions/767733/converting-a-net-funct-to-a-net-expressionfunct) – Charlieface Jan 02 '21 at 21:49
  • Ok... I found that answer confusing... but it did have a link in it that helped me out. – Brian Rice Jan 03 '21 at 01:18
  • What LINQ are you using (your tags are conflicting): LINQ to SQL / EF 6.x / EF Core 2.0 / 2.1 / 3.x / 5.x? I am guessing LINQ to EF Core 2.x which automatically converts to client side processing when it can't use server side. – NetMage Jan 04 '21 at 19:38
  • @NetMage honestly, I don't know... how can I determine this? – Brian Rice Jan 09 '21 at 20:22
  • Duplicate: [Create Expression from Func](https://stackoverflow.com/questions/9377635/create-expression-from-func) – Gert Arnold Feb 21 '21 at 21:23

1 Answers1

0

This answer helped me out: Create Expression from Func.

Basically I had to wrap the Func in an Expression as follows:

    public int GetCount(Expression<Func<Balance, bool>> predicate)
    {
        return = (from b in _appContext.TableName
                  select b
                  ).Where(predicate).Count();
    }

The same call worked:

    GetCount(p => p.Email == 'test@gmail.com');
Brian Rice
  • 3,107
  • 1
  • 35
  • 53