Using MVC EF, how would I filter results by a field other than the id?
return View(db.Drafts.Where(PublicationId=id));
PublicationId is a column in the Drafts table.
Any help is appreciated.
public ActionResult Index(int id)
{
var drafts = db.Drafts.Where(d => d.PublicationId == id).ToList();
return View(drafts);
}
or if you wanna single draft (coz the id is usually unique):
public ActionResult Index(int id)
{
var draft = db.Drafts.SingleOrDefault(d => d.PublicationId == id);
return View(draft);
}
I'm not sure what your Draft
class looks like, but let's pretend it looks something like this:
public class Draft
{
public int Id { get; set; }
public int PublicationId { get; set; }
public string Name { get; set; }
}
You could write a query like this:
return View(db.Drafts.Where(d => d.Name == "foo"));
This would only return Drafts that had a name of "foo". This by itself probably isn't useful. You would more than likely want to control this by passing data into your controller (query string, form value, route value, etc.):
public ActionResult Index(int id, string filter)
{
return View(db.Drafts.Where(d => d.Name == filter));
}
Or you could filter on multiple properties:
public ActionResult Index(int id, string filter)
{
return View(db.Drafts.Where(d => d.Name == filter && d.PublicationId == id));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With