I am trying to use logical operators in the following lambda expression
int count = dataContext.Users.Count(u => u.ID == 1 && u.Name == "name");
below is the complete function
private void Login(int id, string password)
{
MyDataContext dataContext = new MyDataContext();
int count = dataContext.Users.Count(u => u.ID == 1 && u.Name == "name");
}
I’m using Microsoft SQL Server 2008 Express 2008 Edition and User table looks like
ID int autogenerated
Name string
but Visual Studio 2010 gives the following design time errors “Invalid expression terms”. Any idea what I might be doing wrong?
I get the following error messages
- Error 2 ) expected …\FormAdd.cs 105 123
- Error 3 ; expected …\FormAdd.cs 105 126
- Error 5 ; expected …\FormAdd.cs 105 158
- Error 7 ; expected …\FormAdd.cs 105 202
- Error 4 Invalid expression term ‘)’ …\FormAdd.cs 105 158
- Error 6 Invalid expression term ‘)’ …\FormAdd.cs 105 202
- Error 1 Invalid expression term ‘=>’ …\FormAdd.cs 105 123


The code you show in the screenshot is
This is illegal code, and the part with the
**underneath it is the source of the error.The code you show in the body of your question is
These are different. The first, is incorrect, as the IDE points out to you. The latter, is correct.
The signature for the overload of
Countyou are using isThis means to invoke it on
dataContext.Users, you need to provide aPredicate<User>. APredicate<User>is a function that mapsUsertobool. One way to write this isand then you can say
Another way is to say
This lets you define the predicate inline. It’s a nice feature. Note that the expression that effectively defines the predicate
is the same as in the case of
UserPredicatedefined above.And finally, Lambda expressions allow you to get rid of some of that unnecessary fluff.
Where
f(u)is an expression inu. One expression that you can use isAgain, the same expression. See, your attempt in the IDE was illegal because you tried to write
and that is clearly not a legal expression.