I am currently using the following code within my controller:
Instructor instructor = db.Instructors.FirstOrDefault(
o => o.UserName == User.Identity.Name);
to select someone by username. My understanding is that I will have trouble using “FirstOrDefault()” if I have user’s with similar user names (i.e. searching for “MrUser” when I have users named “MrUserOne” “MrUserTwo” and “MrUser” may yield “MrUserOne” because it was the ‘first’ search result to show up), If I am correct in my understanding of future difficulties with “FirstOrDefault,” what should I use in it’s place?
Or am I wrong in my understanding of how FirstOrDefault will work?
It appears you don’t quite understand how the
==operator works in this scenario. Assuming theUserNameandNamevalues are bothstringthen==will do an exact ordinal match. The name"MrUser"won’t match"MrUserOne"at all. It will only match"MrUser".That being said this code will return the first user whose
Namevalue exactly matcheso.UserNameornullif none do.