简体   繁体   English

如何在MVC中使用where子句ef

[英]How to use a where clause in MVC ef

Using MVC EF, how would I filter results by a field other than the id? 使用MVC EF,我如何通过id以外的字段过滤结果?

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

PublicationId is a column in the Drafts table. PublicationId是草稿表中的一列。

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): 或者如果你想单一的草稿(因为id通常是唯一的):

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: 我不确定你的Draft类是什么样的,但让我们假装它看起来像这样:

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". 这只会返回名称为“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));
}

Are you familiar with lambdas? 你熟悉lambdas吗? In the lambda of your where clause, you can specify any property you want to. 在where子句的lambda中,您可以指定您想要的任何属性。

return View(db.Drafts.Where(d => d.SomeProperty == value));

I would also consider putting the data your delivering to the page in a model, rather than making the model be the actual POCO model. 我还会考虑将您提供的数据放入模型中的页面,而不是将模型作为实际的POCO模型。 An MVC model drives the display, a POCO model drives your data. MVC模型驱动显示器,POCO模型驱动您的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM