prisoner24601
prisoner24601

Reputation: 249

Why does Select return a boolean?

I'm working with Entity Framework 6 in MVC 5.

I have the following method:

[HttpPost]
public ActionResult UpdateDetails(ApplicationUser applicationUser)
{
    var context = new ApplicationDbContext();
    var user = context.Users.Select(x => x.UserName == applicationUser.UserName).FirstOrDefault();

//etc etc
}

Users is an IDbSet<ApplicationUser>.

Why am I getting a bool back from the Select method?

My expectation would be to get an ApplicationUser object back. Why isn't this the case?

Thanks

Upvotes: 4

Views: 3689

Answers (4)

Henk Mollema
Henk Mollema

Reputation: 46581

Select() projects an element of a sequence. Since x.UserName == applicationUser.UserName returns a bool, the result of the method will be a boolean.

What you want requires the Where method. This filters the sequence based on the specified predicate:

var user = context.Users.Where(x => x.UserName == applicationUser.UserName).FirstOrDefault();

Which can be shortened to:

var user = context.Users.FirstOrDefault(x => x.UserName == applicationUser.UserName);

This is possible, since this overload of FirstOrDefault() takes a filter predicate as second parameter.

Upvotes: 9

Leonel Sanches da Silva
Leonel Sanches da Silva

Reputation: 7230

Select literally selects something inside the arguments. So, if you have an expression that returns a bool, Select will return bool.

Upvotes: 1

Ananthan Unni
Ananthan Unni

Reputation: 1304

It is because you are SELECTing a boolean.

Since there is no requirement specified, I am guessing your requirement from your attempted code.

use the below line.

var user=context.Users.Where(user=>user.UserName==applicationUser.UserName).FirstOrDefault();

Upvotes: 1

Brendan Green
Brendan Green

Reputation: 11924

Your select is returning an object that is the result of the comparison.

Change to:

var user = context.Users.FirstOrDefault(x => x.UserName == applicationUser.UserName);

Upvotes: 1

Related Questions