Operator '&&' cannot be applied to operands of type 'lambda expression' and 'lambda expression

c# entity-framework lambda

Question

I want to retrive all the records that have the IP or MAC addresses or if any of these are Null, so i wrote my method as follow:-

public IQueryable<Technology> AdvanceSearch(string ip = null, string mac = null, int techtype) 
        {
            var relatedresourcesID = entities.NetworkInfoes
                .Where((a => String.IsNullOrEmpty(ip) || a.IPADDRESS.StartsWith(ip)))
                .Where(a2 => String.IsNullOrEmpty(mac) || a2.MACADDRESS.StartsWith(mac)).Select(a3=>a3.WORKSTATIONID);
//code goes here

but i am not sure how will EF transalte the .where ; will it apply the second .Where() only after applying the first .Where clause ?

second question, how i can apply all the checks to be inside one .Where()??

I have tried to re-write my method as follow:-

var relatedresourcesID = entities.NetworkInfoes
                .Where((a => String.IsNullOrEmpty(ip) || a.IPADDRESS.StartsWith(ip)) && (a2 => String.IsNullOrEmpty(mac) || a2.MACADDRESS.StartsWith(mac)) )
                .Select(a3=>a3.WORKSTATIONID);

but i will get the following error :-

Error 18 Operator '&&' cannot be applied to operands of type 'lambda expression' and 'lambda expression' C:\Users\Administrator\documents\visual studio 2012\Projects\TMS\TMS\Models\Repository.cs 914 24 TMS

1
5
10/25/2013 11:23:20 PM

Accepted Answer

You should pass single lambda expression into where operator:

var relatedresourcesID = entities.NetworkInfoes
       .Where(a => (String.IsNullOrEmpty(ip) || a.IPADDRESS.StartsWith(ip)) &&
                   (String.IsNullOrEmpty(mac) || a.MACADDRESS.StartsWith(mac)))
       .Select(a => a.WORKSTATIONID);

NOTE: You don't need to assign new names of parameter in each operator - these scopes do not overlap.

Also don't forget about declarative query syntax, which is more readable (IMHO) and will not use lambdas at all:

var relatedresourcesID = 
     from a in entities.NetworkInfoes
     where (String.IsNullOrEmpty(ip) || a.IPADDRESS.StartsWith(ip)) &&
           (String.IsNullOrEmpty(mac) || a.MACADDRESS.StartsWith(mac))
     select a.WORKSTATIONID;
9
10/25/2013 11:36:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow