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

Asp.net mvc 如何在MVC ef中使用where子句,asp.net-mvc,entity-framework,Asp.net Mvc,Entity Framework,使用MVC EF,如何按id以外的字段过滤结果 return View(db.Drafts.Where(PublicationId=id)); PublicationId是草稿表中的一列 感谢您的帮助 public ActionResult Index(int id) { var drafts = db.Drafts.Where(d => d.PublicationId == id).ToList(); return View(drafts); } 或者,如果您想要单个

使用MVC EF,如何按id以外的字段过滤结果

return View(db.Drafts.Where(PublicationId=id));
PublicationId是草稿表中的一列

感谢您的帮助

public ActionResult Index(int id)
{
    var drafts = db.Drafts.Where(d => d.PublicationId == id).ToList();
    return View(drafts);
}
或者,如果您想要单个草稿(因为id通常是唯一的):


你熟悉兰博达斯吗?在where子句的lambda中,您可以指定要指定的任何属性

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

<>我也会考虑将数据传递给页面中的模型,而不是使模型成为实际的POCO模型。MVC模型驱动显示,POCO模型驱动数据。

我不确定您的
草稿类是什么样子,但让我们假设它看起来像这样:

public class Draft
{
    public int Id { get; set; }
    public int PublicationId { get; set; }
    public string Name { get; set; }
}
return View(db.Drafts.Where(d => d.Name == "foo"));
您可以编写如下查询:

public class Draft
{
    public int Id { get; set; }
    public int PublicationId { get; set; }
    public string Name { get; set; }
}
return View(db.Drafts.Where(d => d.Name == "foo"));
这将只返回名为“foo”的草稿。这本身可能没有什么用处。您很可能希望通过将数据传递到控制器(查询字符串、表单值、路由值等)来控制这一点:

或者,您可以对多个属性进行筛选:

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

非常感谢。这也是一个有用的答案。d变量来自哪里?这封信重要吗?Regards@DannyRancher这是一个lambda表达式。这封信并不重要,但在范围界定方面有一些限制。谢谢。这也是一个很有帮助的答案。那就投票表决吧?:)