简体   繁体   中英

strange behavior in linq to sql to return all rows without filtering

I write this code:

Rep_Regions clsr = new Rep_Regions();
Func<Regions, bool> filter = r => r.RegionID == int.Parse(textBox5.Text);
Regions reg = new Regions();
reg = clsr.FindSingle(filter);

and :

 public Regions FindSingle(Func<Regions, bool> exp)
    {
        using (RepositoryDataContext = new DataClasses1DataContext())
        {
            return RepositoryDataContext.Regions.Where(exp).FirstOrDefault();
        }
    }

this is the query that execute in Sql Server:

SELECT [t0].[RegionID], [t0].[RegionDescription]
FROM [dbo].[Region] AS [t0]

Why the query not filter results and return all rows?

You have used Func<Regions, bool> filter which forces it to use LINQ-to-Objects after running an unfiltered query at the server. To use query composition you must use expression-trees, not delegates.

Change it to:

int regionId= int.Parse(textBox5.Text);
Expression<Func<Regions, bool>> filter = r => r.RegionID == regionId;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM