In MVC, how do you utilize a where clause?

asp.net-mvc entity-framework

Question

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.

1
11
4/18/2012 3:47:47 PM

Accepted Answer

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);
}
17
4/18/2012 3:49:32 PM

Popular Answer

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));
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow