asp.net-mvc 如何在MVC ef中使用where子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10213097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:52:35  来源:igfitidea点击:

How to use a where clause in MVC ef

asp.net-mvcentity-framework

提问by alockrem

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 是 Drafts 表中的一列。

Any help is appreciated.

任何帮助表示赞赏。

回答by Darin Dimitrov

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

回答by Dismissile

I'm not sure what your Draftclass 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". 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.):

这只会返回名称为“foo”的草稿。这本身可能没有用。您很可能希望通过将数据传递到您的控制器(查询字符串、表单值、路由值等)来控制它:

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

回答by mccow002

Are you familiar with lambdas? In the lambda of your where clause, you can specify any property you want to.

你熟悉 lambda 表达式吗?在 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. An MVC model drives the display, a POCO model drives your data.

我还会考虑将您提供给页面的数据放在模型中,而不是使模型成为实际的 POCO 模型。MVC 模型驱动显示,POCO 模型驱动您的数据。