Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a where clause in MVC ef

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.

like image 835
alockrem Avatar asked Apr 18 '12 15:04

alockrem


2 Answers

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);
}
like image 168
Darin Dimitrov Avatar answered Oct 10 '22 15:10

Darin Dimitrov


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));
}
like image 22
Dismissile Avatar answered Oct 10 '22 13:10

Dismissile