Reputation: 923
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
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 duplicateFirstOrDefault()
- returns default if empty or not found, does not throw if duplicateSingle()
- throws exception if empty or not found, throws if duplicate existsSingleOrDefault()
- 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