In MVC, how do you utilize a where clause?

asp.net-mvc entity-framework

Question

How would I filter results with MVC EF using a field other than the id?

return View(db.Drafts.Where(PublicationId=id));

The Drafts database has a column called PublicationId.

We appreciate any assistance.

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

alternatively, if you only want to use one draft (because the id is often 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 don't know what yourDraft What class may look like, but let's assume it does:

public class Draft
{
    public int Id { get; set; }
    public int PublicationId { get; set; }
    public string Name { get; set; }
}

This is how you may phrase your search:

return View(db.Drafts.Where(d => d.Name == "foo"));

This would only show the Drafts with the name "foo." This definitely doesn't help much on its own. Data (such as a query string, form value, route value, etc.) sent to your controller will likely help you manage this:

public ActionResult Index(int id, string filter)
{
    return View(db.Drafts.Where(d => d.Name == filter));
}

Alternately, you might filter using many criteria:

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