I am not sure where shall I use Single
and where shall I use SingleOrDefault
. I understood the definition for both.
Single:
It will always return one row.
If no row found I will get an exception.
If multiple rows found I will get an exception.
SingleOrDefault:
It will always return one row, if not found then default value is returned
(What is the meaning of this DEFAULT VALUE").
If multiple rows then exception.
Question 1: What is the meaning of "It will return default value"
Question 2: When to use Single and when to use SingleOrDefault.
I have a delete function where I have below code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int resumeId)
{
var r = _context
.Resumes
.Where(c => c.ResumeId == resumeId).SingleOrDefault();
_context.Resumes.Remove(r);
_context.SaveChanges();
return RedirectToAction("ResumeCenter");
}
I just blindly put SingleOrDefault
everywhere (where I ATMOST expect one value), Please tell me a real world scenario when I should use "Single" and where I should use "SingleOrDefault".