为什么Select返回一个布尔值?

pri*_*601 2 c# linq entity-framework-6 asp.net-mvc-5

我正在使用MVC 5中的Entity Framework 6.

我有以下方法:

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

//etc etc
}
Run Code Online (Sandbox Code Playgroud)

用户是一个IDbSet<ApplicationUser>.

为什么我从Select方法中得到一个bool?

我的期望是找回一个ApplicationUser物体.为什么不是这种情况?

谢谢

Hen*_*ema 7

Select()投射序列的元素.由于x.UserName == applicationUser.UserName返回a bool,该方法的结果将是一个布尔值.

你想要什么需要这个Where方法.这会根据指定的谓词过滤序列:

var user = context.Users.Where(x => x.UserName == applicationUser.UserName).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

哪些可以缩短为:

var user = context.Users.FirstOrDefault(x => x.UserName == applicationUser.UserName);
Run Code Online (Sandbox Code Playgroud)

这是可能的,因为过载FirstOrDefault()将过滤谓词作为第二个参数.