Azad
Azad

Reputation: 407

how to compare an integer with a lambda?

public static bool StudentUpdate(string studentId)
{
    using (var db = new UniversityContext())
    {
        int idtoupdate = Convert.ToInt32(studentId);
        Student temp = db.Students.Where((a => a.Id) == idtoupdate)
                                  .SingleOrDefault();
        if (temp != null)
        {
            temp.FirstName = feilds[0];
            temp.LastName = feilds[1];
            temp.Average = Convert.ToSingle(feilds[2]);
            db.SaveChanges();
            return true;
        }
    }
    return false;
}

I need to update some information stored on a database using entity framework but when I try this code I get the following error message:

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

what can I do to solve this problem?

Upvotes: 0

Views: 3013

Answers (3)

phuzi
phuzi

Reputation: 13060

You've got bracket in the wrong place it should be Where((a) => a.Id == idtoupdate).

Also, as Ulugbek notes, for a single parameter the brackets aren't necessary and you could do Where(a => a.Id == idtoupdate).

Upvotes: 0

ClickRick
ClickRick

Reputation: 1569

The lambda

a => a.Id

is equivalent to

delegate(Student a) { return a.Id; }

i.e. it takes a Student and returns the Id of that student. On the other hand, the lambda

a => a.Id == idtoupdate

is equivalent to

delegate(Student a) { return a.Id == idtoupdate; }

and returns a bool value indicating whether or not that Student has the Id you want to match.

Where you can get the hint as to which you should use is in the definition of the Where extension method, which is documented as taking a Func<int, bool> predicate, i.e. a function which takes an int (the Id you want to match) and returns a bool (i.e. whether or not each one matches the supplied Id).

Upvotes: 0

SoftwareFactor
SoftwareFactor

Reputation: 8588

Try:

Student temp = db.Students.Where(a => a.Id == idtoupdate).SingleOrDefault();

Upvotes: 4

Related Questions