Try with,
User myUser = myDBContext.Users.SingleOrDefault(user => user.Username == username);
Use SingleOrDefault insted of Single. If user doesn’t exist then Single will throw an error. While SingleOrDefault will return null if user not found otherwise User object will be return.
Selection Between SingleOrDefault and FirstOrDefault
You can get the user object by using SingleOrDefault and FirstOrDefault but while selecting which method to use consider below points.
- Both return only one value from collection/database if exist otherwise default value.
- But if you have more than one user with same name and you are expecting to get an exception while performing LINQ query then use
SingleOrDefaultas it will thrown an exception if there are more than one element available. - And if you don’t want exception and/or you don’t want to check that your collection/database have duplication of data, just want to get first value from collection/database then use
FirstOrDefaultfor better performance compare toSingleOrDefault
FirstOrDefault
- Generally
FirstOrDefaultorFirstused when we required single value (first) from the collection or database. - In the case of First / FirstOrDefault, only one row is retrieved from the database so it performs slightly better than single / SingleOrDefault. such a small difference is hardly noticeable but when table contain large number of column and row, at this time performance is noticeable.
Some other remarks
- If
usernameis primary key then I think there will be no (significant) difference betweenSingleOrDefaultandFirstOrDefaultperformance as primary key has index and search on index column will always be faster than normal column. SingleorSingleOrDefaultwill generate a regular TSQL like “SELECT …”.- The
FirstorFirstOrDefaultmethod will generate the TSQL statment like “SELECT TOP 1…”