Hello I have always struggled with Lambda expressions in LINQ. I am trying to understand the following code that I found online . I know this might be a stupid question but I did try to read the documentation but couldnt understand much. I would be highly grateful if you could explain in simple words.
This is the controller code of a simple login page application
This is the model class:
I know that
are LINQ queries. The first line is fetching the list of users and the second line is filtering that list of users.
I am not able to understand that how is the first line able to fetch user list from the database. Like how does "m" will fetch the user list?
In the documentation here Part 7, add search to an ASP.NET Core MVC app
it is written that "The query is only defined at this point, it has not been run against the database." So, when does it run against the database?
Secondly, what is the difference between s.username and login.username?
and why are they comparing User.First().password == login.password? Are they comparing one user with the entire list of users?
This is the controller code of a simple login page application
C#:
[HttpPost]
public async Task<IActionResult> Login(Login login)
{
if (ModelState.IsValid)
{
var User = from m in _context.Login select m;
User = User.Where(s => s.username.Contains(login.username));
if (User.Count() != 0)
{
if (User.First().password == login.password)
{
return RedirectToAction("Main","Main");
}
}
}
return RedirectToAction("LoginFailed");
}
This is the model class:
C#:
[Table("users")]
public class Login
{
[Key]
public int userId { get; set; }
[Required(ErrorMessage = "Username is requried!")]
public string username { get; set; }
[Required(ErrorMessage = "Password is requried!")]
public string password { get; set; }
}
I know that
C#:
var User = from m in _context.Login select m;
User = User.Where(s => s.username.Contains(login.username));
are LINQ queries. The first line is fetching the list of users and the second line is filtering that list of users.
I am not able to understand that how is the first line able to fetch user list from the database. Like how does "m" will fetch the user list?
In the documentation here Part 7, add search to an ASP.NET Core MVC app
it is written that "The query is only defined at this point, it has not been run against the database." So, when does it run against the database?
Secondly, what is the difference between s.username and login.username?
and why are they comparing User.First().password == login.password? Are they comparing one user with the entire list of users?