Anthony
Anthony

Reputation: 923

Filtering results by user name

I have this code:

// GET: Teachers/Edit/5
public ActionResult Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    string uname = User.Identity.GetUserId();
    Teachers teachers = db.teachers.Find(id);
    if (teachers == null)
    {
        return HttpNotFound();
    }
    ViewBag.GroupID = new SelectList(db.groups, "GroupID", "GroupName", teachers.GroupID);
    return View(teachers);
}

I am attempting to filter my returned results by id (which is my DB key) but also by the user name which is also stored into the database but not as a key.

I'm not sure of the syntax, but I am pretty sure find is not the way to go.

Upvotes: 0

Views: 73

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

You can use SingleOrDefault:

db.teachers.SingleOrDefault(x => x.ID == id && x.UserName == username);

It returns a single, specific element of a sequence, or a default value if that element is not found. It will throw exception if there is more than one element in the result.

Additionally, you can also use Single(), First(), FirstOrDefault() in such places. Here is the differences between them:

  • First() - throws exception if empty or not found, does not throw if duplicate
  • FirstOrDefault() - returns default if empty or not found, does not throw if duplicate
  • Single() - throws exception if empty or not found, throws if duplicate exists
  • SingleOrDefault() - returns default if empty or not found, throws if duplicate exists

P.S: You haven't stated your column names. So, I have just guessed their names. You can change them as you wish.

Upvotes: 3

Related Questions