Skip to content

Using Func<> for where predicate does not work #12765

Closed as not planned
Closed as not planned

Description

@bastien-besson

I'm trying to retrieve specific data from my table using a predicate. The researched sql query is as follow :
SELECT [plan].[Id] FROM [Plan] AS [plan] WHERE [plan].[IdCampagne] = 39

Plan is a table with columns

  • Id [int]
  • IdCampagne[int]
  • OtherStuff [int]

Steps to reproduce

  1. WORKING CODE
 var a = _context.Plan.AsNoTracking()
                    .Where(plan => plan.IdCampagne == 39)
                    .Select(plan => new { Id = plan.Id })
                    .ToList();

gives :
SELECT [plan].[Id] FROM [Plan] AS [plan] WHERE [plan].[IdCampagne] = 39

  1. NOT WORKING CODE
Func<Plan, bool> predicate = p => p.IdCampagne == 39;
var a = _context.Plan.AsNoTracking()
        .Where(predicate)
        .Select(plan => new { Id = plan.Id })
        .ToList();

gives :
SELECT [p].[Id], [p].[IdCampagne], [p].[OtherStuff] FROM [Plan] AS [p]

Further technical details

EF Core version: 2.1.1
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows Server 2012 R2 Standard
IDE: Visual Studio 2017 15.7.5

Activity

  1. smitpatel commented on Jul 23, 2018

    @smitpatel
    Contributor

    You need to create lambda of Expression<Func<Plan, bool>>. Raw Func<> are opaque in expression tree and we cannot look what is inside. Using Expression<Func<>> integrate the lambda inside the expression with inner body.

  2. changed the title [-]"Where" query does not work as expected in specific case[/-] [+]Using Func<> for where predicate does not work[/+] on Jul 23, 2018
  3. bastien-besson commented on Jul 24, 2018

    @bastien-besson
    Author

    Thanks @smitpatel for your fast answer.

    I feel like the understanding of this behavior is far from evident, and as in one case the whole table is retrieved and in the other not, I guess this will cause problems in many architecture.
    Isn't there maybe a way to promote a better understanding of this difference ?

  4. smitpatel commented on Jul 24, 2018

    @smitpatel
    Contributor

    The difference has nothing specific to EF Core as such. It is about difference in IQueryable vs IEnumerable. For any translation framework to work correctly, you would require IQueryable (Expression<Func<>>) type constructs. Above query would fail to work correctly even in other ORMs or linq to SQL translations.
    If you have ideas about how to educate customers about this then please share.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions