Reputation: 13616
I have this LINQ:
private static IQueryable<Contract> getValidContracts(DbContext context, DateTime date,int clientId)
{
return (from contract in context.Set<Contract>()
where contract.ValidityDate >= date
where contract.ClientId == clientId
select contract);
}
in LINQ I gave this row:
where contract.ClientId == clientId
I want this row will be included in where clause only if clientId variable not equal to zero.
Any idea how can I lmake it elegant?
Upvotes: 1
Views: 888
Reputation: 3018
you can modify the condition as:
where ((clientId!=0)?(contract.ClientId == clientId):true)
Upvotes: 1
Reputation: 205619
For dynamic queries it's better to use the fluent syntax. In this particular case, you can use something like this
private static IQueryable<Contract> getValidContracts(DbContext context, DateTime date, int clientId)
{
var query = context.Set<Contract>().Where(contract => contract.ValidityDate >= date);
if (clientId != 0)
query = query.Where(contract => contract.ClientId == clientId);
return query;
}
Upvotes: 2
Reputation: 29026
Since client id is an external variable you can check it outside the LINQ:
if(clientId==0)
{
return (from contract in context.Set<Contract>()
where contract.ValidityDate >= date
select contract);
}
else
{
return (from contract in context.Set<Contract>()
where contract.ValidityDate >= date
where contract.ClientId == clientId
select contract);
}
Upvotes: 2
Reputation: 3681
Just add a check for 0 in the where
where ((contract.ClientId == clientId && clientId != 0) || clientId == 0)
Upvotes: 7